Return the length of the shortest, non-empty, contiguous subarray of A
with sum at least K
.
If there is no non-empty subarray with sum at least K
, return -1
.
Example 1:
Input: A = [1], K = 1
Output: 1
Example 2:
Input: A = [1,2], K = 4
Output: -1
Example 3:
Input: A = [2,-1,2], K = 3
Output: 3
Note:
1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9
暴力的方法O(N^2),注意到index为i位置的要与i之前那些比;一个优化的思路是:能不能维护一个数据结构避免重复的计算量?然后这个数据结构里面的数都是排好序的,一般就可以有stack,queue,deque
思考一下用 单调递增stack+二分 可以解决;
仔细想一下可以继续用deque优化,每次比较把前面的pop掉,因为要求的是最短的,当前i位置算过了,bii更后面的位置也不可能比i位置算得更短了
from collections import deque
class Solution:
def shortestSubarray(self, a, k):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
n = len(a)
s = [0]*(n+1)
for i in range(n): s[i+1]=s[i]+a[i]
dq=deque()
res=n+1
for i,v in enumerate(s):
while dq and s[dq[0]]<=v-k: res=min(res, i-dq.popleft())
while dq and v<=s[dq[-1]]: dq.pop()
dq.append(i)
return res if res!=n+1 else -1
如果把at least改为at most,那就是单调递减
如果是longest,那就不能pop,改为二分