123. Best Time to Buy and Sell Stock III

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0)
            return 0;
        int[][] dp=new int[4][prices.length+1];
        dp[0][0]=dp[2][0]=Integer.MIN_VALUE;
        for(int i=1;i<=prices.length;i++)
        {
            dp[0][i]=Math.max(dp[0][i-1],-prices[i-1]);
            dp[1][i]=Math.max(dp[1][i-1],dp[0][i-1]+prices[i-1]);
            dp[2][i]=Math.max(dp[2][i-1],dp[1][i-1]-prices[i-1]);
            dp[3][i]=Math.max(dp[3][i-1],dp[2][i-1]+prices[i-1]);
        }
        return dp[3][prices.length];
    }
}

 

压缩

class Solution {
    public int maxProfit(int[] prices) {
        int buy1=Integer.MIN_VALUE,buy2=Integer.MIN_VALUE;
        int sell1=0,sell2=0;
        for(int i=0;i<prices.length;i++)
        {
            sell2=Math.max(sell2, buy2+prices[i]);
            buy2=Math.max(buy2, sell1-prices[i]);
            sell1=Math.max(sell1, buy1+prices[i]);
            buy1=Math.max(buy1, -prices[i]);
        }
        return sell2;
    }
}

  

posted @ 2017-10-02 03:22  Weiyu Wang  阅读(113)  评论(0编辑  收藏  举报