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

188. Best Time to Buy and Sell S

作者: 春草恨离 | 来源:发表于2018-04-20 05:03 被阅读0次

    题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
    题目标签:Array,DP
    此题与123. Best Time to Buy and Sell Stock III 相比,交易数量由2个上升至K个,基本思路还是一样,只是现在要同时更新k个buy,k个sell。
    Java代码:

    class Solution {
        public int maxProfit(int k, int[] prices) {
            int len = prices.length;
            if(len==0 || k==0){
                return 0;
            }
            if (k>= len/2){
                return quickSolve(prices);
            }
            
            int[][] statue = new int[k][len];
            // initialize statue[0]
            int buy = -prices[0];
            for (int i=1; i<len; i++){
                statue[0][i] = Math.max(statue[0][i-1], prices[i] + buy);
                buy = Math.max(buy, -prices[i]);
            }
            // fullfill statue
            for (int i=1; i<k; i++){
                buy = -prices[0];
                for (int j=1; j<len; j++){
                    statue[i][j] = Math.max(statue[i][j-1], prices[j] + buy);
                    buy = Math.max(buy, statue[i-1][j-1]-prices[j]);
                }
            }
            return statue[k-1][len-1];
        }
        
        private int quickSolve(int[] prices){
            int len = prices.length;
            int res = 0;
            for(int i=1; i<len; i++){
                int p1 = prices[i-1];
                int p2 = prices[i];
                if(p2>p1){
                    res += p2-p1;
                }
            }
            return res;
        }
    }
    

    Edge case:

    k = 0
    prices = []
    k>=prices.length/2
    

    相关文章

      网友评论

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

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