Skip to content

Instantly share code, notes, and snippets.

@blacksheep557
Created August 31, 2021 05:56
Show Gist options
  • Select an option

  • Save blacksheep557/b4adc7c55ad3005eabd49ac42609bb40 to your computer and use it in GitHub Desktop.

Select an option

Save blacksheep557/b4adc7c55ad3005eabd49ac42609bb40 to your computer and use it in GitHub Desktop.
function maxSubarray(arr, k) {
if (arr.length < k) return 0
let currSubSum = arr.slice(0, k).reduce((a, b) => a + b);
let sum = currSubSum;
for (let i = k; i < arr.length; i++) {
currSubSum = currSubSum + arr[i] - arr[i - k]
sum = Math.max(sum, currSubSum)
}
return sum
}
console.log(maxSubarray([100, 200, 300, 400], 2));
console.log(maxSubarray([1, 2, -1, 4, -8, 2], 3));
function getLeaders(arr) {
let rightMax = 0;
const res = [];
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] > rightMax) {
rightMax = arr[i]
res.unshift(rightMax)
}
}
return res
}
console.log(getLeaders([8, 1, 3, 4, 2]))
console.log(getLeaders([16, 17, 4, 3, 5, 2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment