-
Notifications
You must be signed in to change notification settings - Fork 0
/
minSubArrayLen.js
28 lines (26 loc) · 954 Bytes
/
minSubArrayLen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Task: write a function which accepts two parameters, an array of positive integers and a positive integer
// This function should return the minimal length of a contiguous subarray or which the sum is greater than or equal to the integer passed to the function. If there isn't one, return 0 instead
const minSubArrayLen = (nums, sum) => {
let total = 0;
let start = 0;
let end = 0;
let minLen = Infinity;
while (start < nums.length) {
if (total < sum && end < nums.length) {
total += nums[end];
end++;
}
// if current window adds up to at least the sum given then
// we can shrink the window
else if (total >= sum) {
minLen = Math.min(minLen, end - start);
total -= nums[start];
start++;
}
// current total less than required total but we reach the end, need this or else we'll be in an infinite loop
else {
break;
}
}
return minLen === Infinity ? 0 : minLen;
};