Created
August 4, 2016 10:14
-
-
Save HopefulLlama/189d08e7148df0bc61b7784d54cea2aa to your computer and use it in GitHub Desktop.
Finds the largest sum of sub-arrays, given an array of integers (Not allowing for zero length sub-arrays).
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
function maxContiguousSubArray(array) { | |
var maxEndingHere = array[0]; | |
var maxSoFar = array[0]; | |
for(var i = 1; i < array.length; i++) { | |
maxEndingHere = Math.max(array[i], maxEndingHere + array[i]); | |
maxSoFar = Math.max(maxSoFar, maxEndingHere); | |
} | |
return maxSoFar; | |
} | |
function maxNonContiguousSubArray(array) { | |
var maximumValue = -Infinity; | |
var subArrayValue = array.reduce(function(previousValue, currentValue) { | |
var value = (currentValue > 0) ? currentValue : 0; | |
maximumValue = Math.max(maximumValue, currentValue); | |
return previousValue += value; | |
}, 0); | |
if(maximumValue < 0) { | |
return maximumValue; | |
} else { | |
return subArrayValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sourced from:
https://en.wikipedia.org/wiki/Maximum_subarray_problem
Last modified:
03 August 2016
Last accessed:
04 August 2016