Skip to content

Commit b9fd4f8

Browse files
Add input validation to longest subarray sum algorithm
1 parent ddf6fb2 commit b9fd4f8

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Sliding-Windows/LongestSubarrayWithSumAtMost.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,32 @@
66
* @returns {number} - The length of the longest subarray with a sum <= target.
77
*/
88
export function longestSubarrayWithSumAtMost(arr, target) {
9+
if (!Array.isArray(arr)) {
10+
throw new TypeError('First argument must be an array')
11+
}
12+
13+
if (typeof target !== 'number') {
14+
throw new TypeError('Target must be a number')
15+
}
16+
17+
if (arr.length === 0) {
18+
return 0
19+
}
20+
921
let maxLength = 0
1022
let windowSum = 0
1123
let left = 0
24+
1225
for (let right = 0; right < arr.length; right++) {
1326
windowSum += arr[right]
27+
1428
while (windowSum > target) {
1529
windowSum -= arr[left]
1630
left++
1731
}
32+
1833
maxLength = Math.max(maxLength, right - left + 1)
1934
}
35+
2036
return maxLength
2137
}

0 commit comments

Comments
 (0)