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

来源:互联网 发布:苹果6手机壳淘宝 编辑:程序博客网 时间:2024/05/01 14:39

Say you have an array for which the ith element is the price of a given stock on dayi.

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;    }




0 0
原创粉丝点击