Skip to content

Instantly share code, notes, and snippets.

@AllThingsSmitty
Last active November 15, 2015 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllThingsSmitty/75de0718b24bee226111 to your computer and use it in GitHub Desktop.
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
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