Yet another DP solution in C++


  • 1
    Q

    The equation is:

    result[N] = max(result[N-1], result[N-2] + num[N])

    int rob(vector<int> &num) {
        int n = num.size();
        if (!n) return 0;
        if (n < 2) return num[0];
        
        vector<int> result(n);
        result[0] = num[0];
        result[1] = max(num[0], num[1]);
        
        for (int i = 2; i < n; i++){
            result[i] = max(result[i-1], result[i-2]+num[i]);
        }
        
        return result[n-1];
    }
    

    For example, for case num == [2, 1, 1, 2]:

    result[0] = num[0] = 2
    result[1] = max(result[0], num[1]) = max(2,1) = 2
    .
    .
    result[3] = max(result[2], result[1] + num[3]) = max(3, 4) = 4
    .


  • 0
    X

    very good thx,so the key to slove dynamic programing is to find the equation


Log in to reply
 

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