Skip to content

Commit 6f8f004

Browse files
authored
Create 862-shortest-subarray-with-sum-at-least-k.js
1 parent d3389b9 commit 6f8f004

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} A
3+
* @param {number} K
4+
* @return {number}
5+
*/
6+
const shortestSubarray = function(A, K) {
7+
const N = A.length
8+
const P = new Array(N+1).fill(0)
9+
10+
for(let i = 0; i < N; i++) {
11+
P[i+1] = P[i] + A[i]
12+
}
13+
14+
let ans = N + 1
15+
const monoq = []
16+
for(let y = 0; y < P.length; y++) {
17+
while(monoq.length > 0 && P[y] <= P[monoq[monoq.length - 1]] ) {
18+
monoq.pop()
19+
}
20+
while(monoq.length > 0 && P[y] >= P[monoq[0]] + K ) {
21+
ans = Math.min(ans, y - monoq.shift())
22+
}
23+
monoq.push(y)
24+
}
25+
26+
return ans < N + 1 ? ans : -1
27+
};

0 commit comments

Comments
 (0)