-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathminSizeSubarraySum.js
More file actions
31 lines (24 loc) · 792 Bytes
/
minSizeSubarraySum.js
File metadata and controls
31 lines (24 loc) · 792 Bytes
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
// Sliding window: TC: O(n), SC: O(1)
function minSizeSubarraySum(nums, target) {
let left = 0, right = 0, total = 0;
let minLength = Infinity;
while(right < nums.length) {
total += nums[right];
while(total >= target) {
minLength = Math.min(right - left + 1, minLength);
total -= nums[left++];
}
right++;
}
return minLength === Infinity ? 0 : minLength;
}
// Test Cases
const testCases = [
{ target: 7, nums: [2, 4, 1, 2, 4, 3] },
{ target: 5, nums: [1, 5, 5, 5] },
{ target: 15, nums: [2, 2, 2, 2, 2] }
];
for (const { target, nums } of testCases) {
console.log(`Input: target = ${target}, nums = [${nums}]`);
console.log(`Output: ${minSizeSubarraySum(nums, target)}\n`);
}