Skip to content

Instantly share code, notes, and snippets.

@achacttn
Last active September 28, 2020 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achacttn/3118be17d50116e5880c171a64045fab to your computer and use it in GitHub Desktop.
Save achacttn/3118be17d50116e5880c171a64045fab to your computer and use it in GitHub Desktop.
Longest subarray with sum <= k
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
@achacttn
Copy link
Author

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] to currentSum 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment