862. Shortest Subarray with Sum at Least K

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. 1 <= A.length <= 50000
  2. -10 ^ 5 <= A[i] <= 10 ^ 5
  3. 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,改为二分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值