188. Best Time to Buy and Sell Stock IV

題目鏈接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
題目標簽:Array,DP
此題與123. Best Time to Buy and Sell Stock III 相比,交易數(shù)量由2個上升至K個,基本思路還是一樣,只是現(xiàn)在要同時更新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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容