Excerpt from the Programmer's Code interview guide
Topic:
Given array of arr and integer num, how many are returned? Array full? The following conditions:
Max (ARR[I...J])-min (ARR[I...J]) <= num
Max (ARR[I...J]) represents the maximum value in the array arr[i...j], min (ARR[I...J]) represents the minimum value in the array arr[i...j].
Exercises
Interval maximum minimum value, immediately associate to the monotonic stack (double-ended queue), but a little more trouble, need to summarize some rules on this basis.
If the array arr[i: J] full condition, i.e. max (Arr[í. _i])-min (arr[i). J]) <=num, then arr[i. J] An array of each of the arr[k. L] (I<=K<=|<=J) are full of conditions we use the array arr[i. J-1] For example, Arr[i. J-1] The most value is only possible, or equal to Arr[i. J] Maximum value, arr[i. J-1] The minimum value may only be greater than or equal to arr[i. J] of the minimum value, so arr[i. J-|] Must be full of conditions, in the same vein, Arr[i. J] Each of the? Array is full? conditions
If the array arr[i: J] dissatisfaction? condition, then all inclusive arr[i. J] of an array, that is, arr[k. L] (k<=i<=j<=|) are dissatisfied? conditions. Proof process with first conclusion
In other words, this problem also satisfies a property, that is, it is important to determine the number of sub-arrays that satisfy the condition based on the subscript range of the two ends
Solution
#include <iostream>#include<vector>#include<deque>using namespacestd;intMaxmatchedarray (vector<int> &nums,intnum) {deque<int>Qmax, Qmin; intn =nums.size (); intres =0; inti =0, j =0; while(I <N) { while(J <N) { while(!qmin.empty () && nums[qmin.back ()] >=Nums[j]) qmin.pop_back (); Qmin.push_back (j); while(!qmax.empty () && nums[qmax.back ()] <=Nums[j]) qmax.pop_back (); Qmax.push_back (j); if(Nums[qmax.front ()]-Nums[qmin.front ()] >num) Break; ++J; } if(Qmin.front () = =i) Qmin.pop_front (); if(Qmax.front () = =i) Qmax.pop_front (); Res+ = J-i;//all sub-arrays with Arr[i] as the first element, and the number of satisfied conditions is j-i++i; } returnRes;}intmain () {vector<int> v{8,7, A,5, -,9, -,2,4,6}; intn =3; cout<< Maxmatchedarray (V, N) <<Endl; System ("Pause"); return 0;}
Queue maximum minus the minimum number of sub-arrays equal to num