3 lines solution in JavaScript


  • 3
    L
    return nums.reduce(function(p, n) { 
        return [p[1], Math.max(p[0] + n, p[1])]; 
    }, [0,0])[1];
    

    variable p records previous 2 max values: p[1] is the previous one and p[0] is the one before previous one. p is initialized as [0,0]. variable n is the value at each position.


  • 1
    S

    Super clever! Took me a few minutes to figure out how it worked but nice job!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.