123. Best Time to Buy and Sell S

2016-12-23  本文已影响43人  沉睡至夏

188.IV的一个特例,k=2;

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length ==0)
            return 0;
        int len = prices.length;
        int dp[][] = new int[3][len];
        
        for (int i=1; i<=2; i++) {
            int max_tmp = dp[i-1][0] - prices[0];
            for (int j=1; j<len; j++) {
                dp[i][j] = Math.max(dp[i][j-1], max_tmp + prices[j]);
                max_tmp = Math.max(max_tmp, dp[i-1][j]-prices[j]);
            }
        }
        return dp[2][len-1];
    }
}
上一篇下一篇

猜你喜欢

热点阅读