We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ddf6fb2 commit b9fd4f8Copy full SHA for b9fd4f8
Sliding-Windows/LongestSubarrayWithSumAtMost.js
@@ -6,16 +6,32 @@
6
* @returns {number} - The length of the longest subarray with a sum <= target.
7
*/
8
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
21
let maxLength = 0
22
let windowSum = 0
23
let left = 0
24
25
for (let right = 0; right < arr.length; right++) {
26
windowSum += arr[right]
27
28
while (windowSum > target) {
29
windowSum -= arr[left]
30
left++
31
}
32
33
maxLength = Math.max(maxLength, right - left + 1)
34
35
36
return maxLength
37
0 commit comments