Last active
February 9, 2017 19:23
-
-
Save fitzk/515c8beb9147660e03651cb3bf72049e to your computer and use it in GitHub Desktop.
Maximum Sub Array Contiguous, a Greedy Implementation
This file contains hidden or 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
const trivialCase = [ 5, -6, 7, 12, -3, 0, -11, -6 ]; | |
function sumValues(a, b) { | |
return a + b | |
} | |
function sumSubArraysStartingAtValue(arr, i) { | |
let sums = [] | |
for(let j = i+1; j < arr.length; j++ ) { | |
if(sums.length > 1) { | |
let lastValueInSums = sums[sums.length-1] | |
sums.push(sumValues(lastValueInSums, arr[j])) | |
} else { | |
sums.push(arr[j]) | |
} | |
} | |
return sums | |
} | |
function getGreatestSum(sums) { | |
return Math.max(...sums) | |
} | |
function sumAllSubArrays(arr) { | |
let netSums = [] | |
let greatestSum = -Infinity; | |
for(let i = 0; i < arr.length; i++ ) { | |
let temp = sumSubArraysStartingAtValue(arr, i) | |
let currentGreatestSum = getGreatestSum(temp) | |
if(greatestSum < currentGreatestSum){ | |
greatestSum = currentGreatestSum | |
} | |
} | |
return greatestSum; | |
} | |
function runner(trivialCase){ | |
return sumAllSubArrays(trivialCase) | |
} | |
runner(trivialCase) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment