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).
题目:最佳时间买入卖出股票:你有一个数组保存了股票在第i天的价钱,现在你最多进行K次买卖,但同一时间你手上只能保持一个股票,如何赚的最多?
分析:使用动态规划。local[j]和global[j]表示到第i天,进行j次交易可获取的最大利润。local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); 当到第i天时候,手上若不持有股票,所以第i天买股票,或者不买股票,如果diff = prices[i + 1] - prices[i]>0的时候,就买股票,因为可以赚钱,如果小于0就不买,因为赔钱,此时global[j - 1] + Math.max(diff, 0),这个就是i天不持股票的情况(相当于i-1天的时候股票抛掉),因为我们算得是进行j次交易嘛,第i天还要买一次所以是global[j - 1] + Math.max(diff, 0)。如果第i天手上继续持有以前买的股票,而且也是进行j次交易,等于是第i天前已经进行过的j次交易的最大值,继续持有,不卖,所以是local[j] + diff。
public int maxProfit(int k, int[] prices) {
if (prices.length < 2 || k <= 0)
return 0;
//纯粹for pass leetcode online judge,因为k == 1000000000时会内存溢出
//pass leetcode online judge (can be ignored)
if (k > prices.length / 3) {//可以买卖不限次数
int res = 0;
for (int i = 1; i < prices.length; i++) {
int profit = prices[i] - prices[i - 1];
if (profit > 0) res += profit;
}
return res;
}
int[] local = new int[k + 1], 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(local[j], global[j]);
}
}
return global[k];
}