[LeetCode] 862. Shortest Subarray with Sum at Least K

Problem

Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.code

If there is no non-empty subarray with sum at least K, return -1.隊列

Example 1:get

Input: A = [1], K = 1
Output: 1
Example 2:it

Input: A = [1,2], K = 4
Output: -1
Example 3:io

Input: A = [2,-1,2], K = 3
Output: 3ast

Note:class

1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9test

Solution

class Solution {
    public int shortestSubarray(int[] nums, int k) {
        if (nums == null || nums.length == 0) return -1;
        int len = nums.length, min = len+1;
        int[] sum = new int[len+1];
        for (int i = 0; i < len; i++) sum[i+1] = sum[i] + nums[i];
        Deque<Integer> queue = new ArrayDeque<>();
        // pollFirst() == poll()    較早放入deque的元素 在隊列頂部
        // getFirst() == peek()
        // pollLast()               最近放入deque的元素 在隊列尾部
        // getLast()
        for (int i = 0; i <= len; i++) {
            // 檢查最近放入的index,保證隊列中新放入的index及對應的sum[index]均爲遞增
            // 反證:若保留worse candidate,那麼在下面第二個while循環,該元素有可能
            // 中斷while循環,並使得咱們沒法獲得隊列更左邊的最優解
            while (queue.size() > 0 && sum[i]-sum[queue.getLast()] <= 0) {
                queue.pollLast();
            }
            // 檢查較早放入的index update最小距離
            while (queue.size() > 0 && sum[i]-sum[queue.peek()] >= k) {
                min = Math.min(min, i-queue.peek());
                queue.pollFirst();
            }
            
            queue.offer(i);
        }
        return min <= len ? min : -1;
    }
}
相關文章
相關標籤/搜索