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 :
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
Post a Comment