Snippets

Steven Berlan Max Contiguous / Non-contiguous lists

Created by Steven Berlan
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;
    };
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.