Max Array Sum

  • + 0 comments

    Here is a node solution. I tried to make it as readable as possible: For Dynamic Programmin, you want to keep track of the base cases before you start looping. During your looping, you still want to keep track of what you are looking for on each index so that the later indexes can access them without needing to do recalculations. It is crutial to do as little calculations as possible. Take a look:

    function maxSubsetSum(arr) {
       let pointerIndex = 2;
       let maxSubsetSum = Math.max(arr[0], arr[1]);
       let positionMaxes = {
           0: arr[0],
           1: Math.max(arr[1], arr[0]),
        };
       
        while(pointerIndex < arr.length) {
            if(positionMaxes[pointerIndex]) {
                pointer++;
            }
            positionMaxes[pointerIndex] = Math.max(arr[pointerIndex], positionMaxes[pointerIndex-2] + arr[pointerIndex], maxSubsetSum)
            
            maxSubsetSum = Math.max(maxSubsetSum, positionMaxes[pointerIndex])
            
            pointerIndex++;
        }
    
        return maxSubsetSum;
    }