Last active
November 15, 2015 14:36
-
-
Save AllThingsSmitty/75de0718b24bee226111 to your computer and use it in GitHub Desktop.
Given an array of integers (positive or negative) find the sub-array with the largest sum
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
var list = [ | |
2, -4, | |
6, -9, [8, 9, -6], | |
12, [45, 3, 7], -34, [7, -2] | |
]; | |
sublists = []; | |
sublists_sum = []; | |
for (var i in list) { | |
if (Object.prototype.toString.call(list[i]) == '[object Array]') { | |
sublistssum = list[i].reduce(function (a, b) { | |
return a + b; | |
}); | |
sublists[sublistssum] = list[i]; | |
sublists_sum.push(sublistssum); | |
} | |
} | |
var max_item = Math.max.apply(null, sublists_sum); | |
alert('sub-array with the largest sum is ' + sublists[max_item]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment