Skip to content

Instantly share code, notes, and snippets.

@ivaylopivanov
Last active July 11, 2020 18:56
Show Gist options
  • Save ivaylopivanov/547bafa0b8e4da6749176078730307f5 to your computer and use it in GitHub Desktop.
Save ivaylopivanov/547bafa0b8e4da6749176078730307f5 to your computer and use it in GitHub Desktop.
Window Sliding Technique
// https://www.geeksforgeeks.org/longest-subarray-sum-elements-atmost-k/
function maxLength(arr, k) {
let sum = 0;
let cnt = 0;
let maxLength = 0;
const arrL = arr.length;
for (let i = 0; i < arrL; i++) {
sum += arr[i];
if (k >= sum) {
cnt += 1;
} else if (sum != 0) {
// deduct the first el
sum -= arr[i - cnt];
}
maxLength = Math.max(cnt, maxLength);
}
return maxLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment