给定一个元素都是正整数的数组A
,正整数 L
以及 R
(L <= R
)。
求连续、非空且其中最大元素满足大于等于L
小于等于R
的子数组个数。
例如 :
输入:
A = [2, 1, 4, 3]
L = 2
R = 3
输出: 3
解释: 满足条件的子数组: [2], [2, 1], [3].
注意:
L, R 和 A[i]
都是整数,范围在 [0, 10^9]
。
数组 A
的长度范围在[1, 50000]
。
思路:数学问题,找到规律即可。当数组元素大于R时,可作为分界线,在子区间寻找满足条件的子数组。
C++
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R)
{
int n=A.size();
int res=0;
int first=0;
int tmp=0;
for(int i=0;i<n;i++)
{
if(A[i]>R)
{
first=i+1;
tmp=0;
continue;
}
else if(A[i]>=L && A[i]<=R)
{
tmp=i-first+1;
res+=tmp;
}
else
{
if(tmp>0)
{
res+=tmp;
}
}
}
return res;
}
};
python
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
n=len(A)
res=0
tmp=0
first=0
for i in range(n):
if A[i]>R:
first=i+1
tmp=0
continue
elif A[i]>=L and A[i]<=R:
tmp=i-first+1
res+=tmp
else:
if tmp>0:
res+=tmp
return res