188. Best Time to Buy and Sell Stock IV

class Solution {
    public int maxProfit(int k, int[] prices) {
        if(k>=prices.length/2)
        {
            int maxProfit=0;
            for(int i=1;i<prices.length;i++)
                maxProfit+=prices[i]>prices[i-1]?prices[i]-prices[i-1]:0;
            return maxProfit;
        }
        int[] buys=new int[k];
        Arrays.fill(buys, Integer.MIN_VALUE);
        int[] sells=new int[k];
        for(int p: prices)
        {
            for(int i=k-1;i>=0;i--)
            {
                sells[i]=Math.max(sells[i], buys[i]+p);
                if(i==0)
                    buys[i]=Math.max(buys[i], -p);
                else
                    buys[i]=Math.max(buys[i], sells[i-1]-p);
            }
        }
        return k>0?sells[k-1]:0;
    }
}

  

posted @ 2017-10-26 01:19  Weiyu Wang  阅读(135)  评论(0编辑  收藏  举报