My DP solution


  • 1
    W

    Defines f[i] = max profit we can get at the end of day i
    In day i+1, we can

    • do nothing, f[i+1] = f[i]
    • sell the stock buy before, f[i+1] = max{f[k] + a[i] - a[k+2]} (buy the stock in day k+2)

    Then we have:

    f[i+1] = max{ f[i], f[k] + a[i] - a[k+2] }, k+2 < i+1
    

    We only need to store the max value of f[k] - a[k+2] (k+2<i+1) in the calculating process.

    f[i+1] = max{ f[i], g[i-1] + a[i] }
    g[i+1] = max{ g[i], f[i-2] - a[i] }
    

    Notice that k may less than 0, and f[i<0] = 0;

    Finally, eliminate the redundant space usage:

    int maxProfit(int* a, int n) {
        int f = 0, f1 = 0, f2 = 0, g = -a[0];
        for (int i=1; i<n; i++) {    
            g = max(g, f2 - a[i]);
            f = max(f1, g + a[i]);
            
            // for next iteration
            f2 = f1;
            f1 = f;
        }
        return f;
    }
    

Log in to reply
 

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