Skip to content

Instantly share code, notes, and snippets.

@alaztetik
Created January 12, 2021 20:18
Show Gist options
  • Save alaztetik/bfec574a34efe346d17587cb2185440f to your computer and use it in GitHub Desktop.
Save alaztetik/bfec574a34efe346d17587cb2185440f to your computer and use it in GitHub Desktop.
Finding the contiguous/continuous subarray of an array argument with the maximal sum of items
// Fast:
function getMaxSubSum(arr) {
let maxSum = 0;
let partialSum = 0;
for (let item of arr) { // for each item of arr
partialSum += item; // add it to partialSum
maxSum = Math.max(maxSum, partialSum); // remember the maximum
if (partialSum < 0) partialSum = 0; // zero if negative
}
return maxSum;
}
// Slow:
function getMaxSubSum(arr) {
let maxSum = 0;
for (let i = 0; i < arr.length; i++) {
let sumFixedStart = 0;
for (let j = i; j < arr.length; j++) {
sumFixedStart += arr[j];
maxSum = Math.max(maxSum, sumFixedStart);
}
}
return maxSum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment