题目描述
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].
Note:
- L, R and
A[i]
will be an integer in the range[0, 10^9]
. - The length of
A
will be in the range of[1, 50000]
.
解题思路
题目含义:给定一个数组,和两个变量L和R,现在要求将给定的数组进行分块,每一块数组必须满足最大值要在[L,R]范围内,包含L和R。
思路:
- 如果当前元素满足在[L,R]范围内,则计算当前元素前面有几个连续的符合条件的数组元素,计算结果放在count中,count的值就可以作为当前元素与前面元素可以拆分的数组个数。
- 如果当前元素的值小于L,则说明当前元素不能单独作为一个数组出现,必须找一个元素值在[L,R]区间的值作为该数组的最大元素,所以当前元素能够差分的数组个数应该与其最接近的值为[L,R]的元素组成的数组个数相同
- 如果当前元素的值超过了R,说明当前元素与前面的元素已经断开,当前元素后面的元素不能与当前元素前面的元素组成连续的子串了。则将count变为0。
AC代码
class Solution {
public int numSubarrayBoundedMax(int[] A, int L, int R) {
if(A == null || A.length == 0)
return 0;
int ret = 0;
int j = 0;
int count = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] >= L && A[i] <= R) {
count = i - j + 1; //当前元素前面有多少个符合条件的<=R的元素值
ret += count;
}else if(A[i] < L) {
ret += count;//如果当前元素不能单独带领数组,那么当前元素插入进来能够组成的数组数与最接近的一个[L,R]元素是相同的
}else{
j = i + 1;
count = 0;
}
}
return ret;
}
}