-
-
Save achacttn/3118be17d50116e5880c171a64045fab to your computer and use it in GitHub Desktop.
Longest subarray with sum <= k
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const longestSubarrayLength = (arr, k) => { | |
let longestLength = 0; | |
for (let i = 0; i < arr.length; i++) { | |
let currentSum = 0; | |
let currentCount = 0; | |
let currentSlice = arr.slice(i); | |
console.log('currentslice: ', currentSlice); | |
// for current slice, add values as long as sum is <= k | |
for (let j = 0; j < currentSlice.length; j++) { | |
if (currentSum + currentSlice[j] <= k) { | |
currentSum += currentSlice[j]; | |
currentCount += 1; | |
} | |
// if next value would cause currentSum to be > k, compare number of values added with longestLengt | |
if (currentCount > longestLength) { | |
longestLength = currentCount | |
} | |
} | |
} | |
console.log('answer: ', longestLength); | |
return longestLength | |
} | |
# updated to add annotations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NB: The above approach would need to be modified if input array contained negative numbers.
As it stands, there is an assumption that adding
currentSlice[j]
tocurrentSum
would only increase.If negative numbers were to be included, the nested loop can check the sum of the entire slice, then remove elements from the end if sum was <= k.