862. Shortest Subarray with Sum at Least K

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.

subarray is a contiguous part of an array.

 Example 1:

Input: nums = [1], k = 1
Output: 1

Example 2:

Input: nums = [1,2], k = 4
Output: -1

Example 3:

Input: nums = [2,-1,2], k = 3
Output: 3

 Constraints:

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105
  • 1 <= k <= 109

C++

  • class Solution {
    public:
        int shortestSubarray(vector<int>& nums, int k) {
            int n = nums.size();
            vector<long> s(n + 1);
            for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i];
            deque<int> q;
            int ans = n + 1;
            for (int i = 0; i <= n; ++i) {
                while (!q.empty() && s[i] - s[q.front()] >= k) {
                    ans = min(ans, i - q.front());
                    q.pop_front();
                }
                while (!q.empty() && s[q.back()] >= s[i]) q.pop_back();
                q.push_back(i);
            }
            return ans > n ? -1 : ans;
        }
    };

JAVA

  • class Solution {
        public int shortestSubarray(int[] nums, int k) {
            int n = nums.length;
            long[] s = new long[n + 1];
            for (int i = 0; i < n; ++i) {
                s[i + 1] = s[i] + nums[i];
            }
            Deque<Integer> q = new ArrayDeque<>();
            int ans = n + 1;
            for (int i = 0; i <= n; ++i) {
                while (!q.isEmpty() && s[i] - s[q.peek()] >= k) {
                    ans = Math.min(ans, i - q.poll());
                }
                while (!q.isEmpty() && s[q.peekLast()] >= s[i]) {
                    q.pollLast();
                }
                q.offer(i);
            }
            return ans > n ? -1 : ans;
        }
    }

PYTHON

  • from collections import deque
    
    class Solution:
        def shortestSubarray(self, nums, k):
            n = len(nums)
            s = [0] * (n + 1)
            for i in range(n):
                s[i + 1] = s[i] + nums[i]
            q = deque()
            ans = n + 1
            for i in range(n + 1):
                while q and s[i] - s[q[0]] >= k:
                    ans = min(ans, i - q.popleft())
                while q and s[q[-1]] >= s[i]:
                    q.pop()
                q.append(i)
            return -1 if ans > n else ans

Comments