1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
function noncontiguousSum(array) { array.sort(function(l, r) { return l - r; }); var value = array.shift() || 0; while (array[0] > 0) value += array.shift(); return value; } function contiguousSum(array) { var best = array[0]; for (var s = 0; s < array.length; ++s) { for (var e = array.length - 1; e > s; --e) { best = Math.max(best, array.slice(s, e).reduce(sum, 0)); } } return best; function sum(previous, value) { return previous + value; }; }
You can clone a snippet to your computer for local editing. Learn more.