LeetCode-Best Time to Buy and Sell Stock IV(JAVA)

Say you have an array for which the i-th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

說明:參考 https://blog.csdn.net/linhuanmars/article/details/23236995

class Solution {
    public int maxProfit(int k, int[] prices) {
        if(prices.length < 2) {
            return 0;
        }        
        if(k >= prices.length) {
            return nmaxp(prices);
        }
        
        //參考:https://blog.csdn.net/xiaocong1990/article/details/80528110 
        int[] global = new int[k + 1];
        int[] local = new int[k + 1];
        for(int i = 1; i < prices.length; i++) {
            int diff = prices[i] - prices[i - 1];
            //因爲local[j]和global[j]的計算需要依賴於i - 1次計算的local[j-1]和global[j -1],所以需要j從高到低進行遍歷,這樣纔不會變
            for(int j = k; j >0; j--) {
                local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
                global[j] = Math.max(local[j], global[j]);
            }
        }
        return global[k];
    }
    
    public int nmaxp(int[] prices) {
        int sum = 0;
        for(int i = 1; i <prices.length; i++) {
            if(prices[i] > prices[i- 1]) {
                sum += prices[i] - prices[i - 1];
            }
        }
        return sum;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章