Created
January 12, 2021 20:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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