-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminSubArrLen.js
More file actions
37 lines (32 loc) · 1.15 KB
/
Copy pathminSubArrLen.js
File metadata and controls
37 lines (32 loc) · 1.15 KB
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
29
30
31
32
33
34
35
36
37
// Write a function called minSubArrayLen which accepts two parameters -
// an array of positive integers and a positive integer.
// This function should return the minimal length of a contiguous subarray of which the sum is greater
// than or equal to the integer passed to the function. If there isn't one, return 0 instead.Examples:
function minSubArrayLen(nums, sum) {
let total = 0;
let start = 0;
let end = 0;
let minLen = Infinity;
while (start < nums.length) {
// if current window doesn't add up to the given sum then
// move the window to right
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;
}
console.log(minSubArrayLen([2, 3, 1, 2, 4, 3], 7));
console.log(minSubArrayLen([2, 1, 6, 5, 4], 9));