[LeetCode 188] Best Time to Buy and Sell Stock IV

Say you have an array for which the ith 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).


solution:

reference: http://blog.csdn.net/linhuanmars/article/details/23236995

global[i][j] means at day i with max j transactions, maximum profit. 

local[i][j] means at day i with max j transactions, and last transaction happened at day i, maximum profit

global[i][j] = max(global[i-1][j], local[i][j]),  diff means last profit.

local[i][j] = max(global[i-1][j] + max(diff,0), local[i-1][j] + diff)

public int maxProfit(int k, int[] prices) {
        int len = prices.length;
        if(k > len) return maxKProfit(prices);
        int[] local = new int[k+1];
        int[] global = new int[k+1];
        for(int i=0;i<prices.length-1;i++) {
            int diff = prices[i+1] - prices[i];
            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];
    }
    public int maxKProfit(int[] prices) {
        int res = 0;
        for(int i=1;i<prices.length;i++) {
            int diff = prices[i] - prices[i-1];
            if(diff>0) res += diff;
        }
        return res;
    }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章