We are given an array A of positive integers, and two positive integers L and R (L <= R).
Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.
Example :
Input:
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
1.题目大意
给定边界值L和R,求解连续子数组的最大值在区间[L,R]范围的个数
2.分析
解决本题的关键地方在于:
根据数组中大于R的元素作为分界划分合理的区间,要考虑重复计算的问题。例如:
L=2, R=3 A=[2,2,1,3,4,3] 可以将其分为 [2,2,1,3] 和 [3],要将不满足条件的子数组去掉。
比较简单的解法:两层循环,第一层循环表示子数组的起点,第二层循环表示添加到子数组的元素,依次往后遍历,如果碰到大于R的元素,则说明添加后面的元素无法满足题目要求。时间复杂度为O(n^2)
下面主要针对关键问题①来进行求解,如果我们仔细去看,可以发现,其实根据大于R的元素去划分区间是比较合理的,难点就在于解决重复的问题。对于n个元素的数组,则有(n+1) * n / 2个子数组;这些子数组包含其中的最大值元素不在[L,R]范围内的数据,所以要将其去除,我们只需去掉最大值小于L的子数组即可。
综上,首先根据大于R的元素进行划分数组;统计数组的所有子数组个数,然后减去最大值小于L的子数组,剩下的即为最大值在[L,R]区间的子数组。例如 [2,1,4,3] L=2 R=3
划分成两个数组 [2,1] 和 [3]
统计[2,1]满足条件的子数组:[2] [2,1] [1] - [1] = [2] [2,1] 共2种
故总共 3 种子数组满足条件
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
return getLessBoundNum(A, R) - getLessBoundNum(A, L - 1);
}
int getLessBoundNum(const vector<int>& A, const int bound) {
int res = 0, cur = 0;
for (int pos = 0; pos < A.size(); ++pos) {
cur = A[pos] <= bound ? cur + 1 : 0;
res += cur;
}
return res;
}
};