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=2, R=4, A=[1,1,1,3]
dp[0]=0, dp[1]=0, dp[2]=0, dp[3]!=dp[2]+1
dp[3]而是=4
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
if not A: return 0
dp = [0 for _ in range(len(A))]
dp[0] = 1 if L<=A[0]<=R else 0
for i in range(1, len(A)):
if A[i]>R: continue
if A[i]<L: dp[i]=dp[i-1]
else:
j = i-1
# 处理遗漏的情况
while j>=0 and A[j]<L: j-=1
dp[i]=dp[i-1]+i-j
return sum(dp)
s=Solution()
print(s.numSubarrayBoundedMax([2,1,4,3], 2, 3))
print(s.numSubarrayBoundedMax([73,55,36,5,55,14,9,7,72,52], 32, 69))
写上面的解法得到的启发
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
res=cnt=prev=0
for i in range(len(A)):
if L<=A[i]<=R:
res+=i-prev+1 # 以i结尾的情况
cnt=i-prev+1 # 多大范围没有比L小或者比R大的
elif A[i]<L:
res+=cnt # 必须要依赖前面一个的
else:
prev=i+1
cnt=0
return res
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
"""
:type A: List[int]
:type L: int
:type R: int
:rtype: int
"""
res=start=prev=0
for i,v in enumerate(A):
if L<=v<=R:
t=i-start+1 # 以当前位置为结果OK的个数
res+=t
prev=t
elif v<L:
res+=prev # 必须以前一个位置结束
else:
start=i+1 # 没有大于R的index开始位置
prev=0
return res