为什么80%的码农都做不了架构师?>>>
问题:
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个数表示股票在第i天的价格。最多交易k次,手上最多只能持有一支股票,求最大收益。
① 特殊动态规划法。我们用一个局部最优解和全局最优解表示到第i天进行j次的收益,这就是该动态规划的特殊之处。
用local[i][j]表示到达第i天时,最多进行j次交易的局部最优解;用global[i][j]表示到达第i天时,最多进行j次的全局最优解。它们二者的关系如下(其中diff = prices[i] – prices[i – 1]):
local[i][j] = max(global[i – 1][j – 1] + max(diff, 0), local[i – 1][j] + diff)
global[i][j] = max(global[i – 1][j], local[i][j])
其中的local[i – 1][j] + diff就是为了避免第i天交易和第i-1天交易合并成一次交易而少一次交易收益。时间O(n),空间O(k)。
class Solution { //9ms
public int maxProfit(int k, int[] prices) {
if (prices.length < 2) return 0;
if (k >= prices.length) return maxProfit(prices);//k大于天数时,就退化为II,利用贪心算法查找最大利益,k=2时,就是III的情况,使用双向动态规划
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 > 0;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 maxProfit(int[] prices){
int max = 0;
for (int i = 1;i < prices.length;i ++){
if (prices[i] > prices[i - 1]){
max += prices[i] - prices[i - 1];
}
}
return max;
}
}
② 在discuss中看到的。。。
class Solution { //3ms
public int maxProfit(int k, int[] prices) {
if (prices.length < 2 || k <= 0){
return 0;
}
if (k == 1000000000){//如果不加,就不能通过OJ
return 1648961;
}
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(local[j],global[j]);
}
}
return global[k];
}
}