美文网首页
123. Best Time to Buy and Sell S

123. Best Time to Buy and Sell S

作者: 沉睡至夏 | 来源:发表于2016-12-23 04:38 被阅读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];
    }
}

相关文章

网友评论

      本文标题:123. Best Time to Buy and Sell S

      本文链接:https://www.haomeiwen.com/subject/uozhvttx.html