We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent eedfe01 commit db77ba8Copy full SHA for db77ba8
solution/0862.Shortest Subarray with Sum at Least K/Solution.java
@@ -0,0 +1,22 @@
1
+class Solution {
2
+ public int shortestSubarray(int[] A, int K) {
3
+ int n = A.length;
4
+ int[] s = new int[n + 1];
5
+ for (int i = 0; i < n; ++i) {
6
+ s[i + 1] = s[i] + A[i];
7
+ }
8
+ Deque<Integer> deque = new ArrayDeque<>();
9
+ deque.offer(0);
10
+ int res = Integer.MAX_VALUE;
11
+ for (int i = 1; i <= n; ++i) {
12
+ while (!deque.isEmpty() && s[i] - s[deque.peekFirst()] >= K) {
13
+ res = Math.min(res, i - deque.pollFirst());
14
15
+ while (!deque.isEmpty() && s[i] <= s[deque.peekLast()]) {
16
+ deque.pollLast();
17
18
+ deque.offer(i);
19
20
+ return res != Integer.MAX_VALUE ? res : -1;
21
22
+}
0 commit comments