Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created December 18, 2017 04:13
Show Gist options
  • Select an option

  • Save aire-con-gas/8d0b8c85360a7ce0697707e42463a309 to your computer and use it in GitHub Desktop.

Select an option

Save aire-con-gas/8d0b8c85360a7ce0697707e42463a309 to your computer and use it in GitHub Desktop.
const largestRunningSum = (inputArr = []) => {
let runningSum = 0;
let maxSum = 0;
inputArr.forEach(item => {
runningSum += item;
if (runningSum > 0 && runningSum > maxSum) {
maxSum = runningSum;
} else if (runningSum < 0) {
runningSum = 0;
}
});
return maxSum;
};
console.log('largestRunningSum([-1, 1, -2])', largestRunningSum([-1, 1, -2])); //returns 1;
console.log('largestRunningSum([4, -1, 3, -6, -10])', largestRunningSum([4, -1, 3, -6, -10])); //returns 6;
console.log('largestRunningSum([1, 2, -3, 6, 4])', largestRunningSum([1, 2, -3, 6, 4])); //returns 6;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment