1. 程式人生 > >LeetCode Best Time to Buy and Sell Stock IV

LeetCode Best Time to Buy and Sell Stock IV

但這裡要注意若是k很大已經超過了prices.length的時候,若是按照DP的方法做會浪費時間以及空間。

AC Java:

public class Solution {
    public int maxProfit(int k, int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        if(k>=prices.length){
            int res = 0;
            for(int i = 1; i < prices.length; i++){
                res += Math.max(0, prices[i]-prices[i-1]);
            }
            return res;
        }
        
        int[] local = new int[k+1];
        int[] global = new int[k+1];
        for(int i = 1; i<prices.length; i++){
            int diff = prices[i] - prices[i-1];
            for(int j = k; j>=1; j--){
                local[j] = Math.max(global[j-1] + Math.max(diff,0), local[j] + diff);
                global[j] = Math.max(global[j], local[j]);
            }
        }
        return global[k];
    }
}