Shortest Subarray with Sum at Least K

Problem Link

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.

Discussion :


 public int shortestSubarray(int[] A, int K) {
    int N = A.length, res = N + 1;
    int[] B = new int[N + 1];
    for (int i = 0; i < N; i++) B[i + 1] = B[i] + A[i];
    Deque<Integer> d = new ArrayDeque<>();
    for (int i = 0; i < N + 1; i++) {
        while (d.size() > 0 && B[i] - B[d.peekFirst()] >=  K)
            res = Math.min(res, i - d.pollFirst());
        while (d.size() > 0 && B[i] <= B[d.peekLast()]) d.pollLast();
        d.addLast(i);
    }
    return res <= N ? res : -1;
}

Comments

Popular posts from this blog

Longest Subarray with Sum greater than Equal to K

Search in Rotated Sorted Array

Consistent Hashing