Q10:Given an integer array nums
and two integers left
and right
, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]
.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example :
Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements:
[2], [2, 1], [3].
Solution:
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
int n = A.size();
stack<int> pge,nge; //Previous greater element(pge) and Next Greater element(nge)
vector<int> left(n,-1);//Stores PGE for index i
vector<int> right(n,n);//Stores NGE for index i
int ans= 0;
for(int i=0;i<n;++i)
{
while(!pge.empty() && A[pge.top()] < A[i])
pge.pop();
if(!pge.empty()) left[i] = pge.top();
pge.push(i);
while(!nge.empty() && A[nge.top()] < A[i]){
right[nge.top()] = i;
nge.pop();
}
nge.push(i);
}
for(int i=0;i<n;++i){
if(A[i] >=L && A[i]<=R){
ans+=(right[i]-i)*(i-left[i]);//Adds contribution of particular index into the ans value
}
}
return ans;
}
};
Explantion:
Processing the Array:
.)The code iterates through the array A.
For each element, it updates the pge and nge stacks and fills the left and right vectors.
It utilizes the stack to efficiently find the previous and next greater elements for each index.
Counting Subarrays:
After the previous processing, the code iterates through the array again.
For each element within the specified range [L, R], it calculates the contribution
of that index to the final count by multiplying the width of the subarray
(difference between right and left indices) by the height (difference between right and current index).
This contribution is added to the total count.
Result:
The final result, i.e., the count of subarrays with a maximum element in the specified range, is returned.
Time Complexity:
The algorithm utilizes a single pass through the array, and the stacks help
maintain the necessary information efficiently. Therefore, the time complexity is O(n), where n is the
size of the input array.