Best Time to Buy and Sell Stock IV - LeetCode
题目:
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).
又找了一道动态规划的题目做。
本来想用一个三维数组a[i][k][f]
来记录前i天交易k次所能获得的最大利润,交易有可能出现半次(只买入而还未卖出),所以数组后面加了一维,a[i][k][1]
表示前i天交易k-1次,外加买入一次所能获得的最大利润,a[i][k][0]
表示前i天交易k次(并且全部卖出)所能获得的最大利润。
当我们知道了前n天的情况,要计算前n+1天时,可以由以下公式推导:
cur = prices[n+1] //今天的价格
a[n+1][k][0] = max(a[n][k][1]+cur, a[n][k][0])
a[n+1][k][1] = max(a[n][k-1][0]-cur, a[n][k][1])
这里有一个问题,数据太大的时候需要一个很大的数组,栈的空间有可能不够(事实上是有不够的时候的),这时就需要优化一下。
注意到当a[i]这一层计算完之后,他们的值就不会再改变了,而计算a[i+1]这一层只需要用到a[i]这一层的值,所以当我们计算完a[i+1]这一层之后,可以覆盖掉a[i]这一层的值,这样就不用另外的存储空间了(实际写代码的时候可以一边计算,一边覆盖)。
下面是代码
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int len = prices.size();
if (len < 2) return 0;
if (k>len/2){
int ans = 0;
for (int i=1; i<len; ++i){
ans += max(prices[i] - prices[i-1],0);
}
return ans;
}
int profit[k+1][2] = {0};
profit[0][0] = 0;
profit[0][1] = 0;
for (int i = 1; i <= k; i++) {
profit[i][0] = 0;
profit[i][1] = -prices[0];
}
int i, j;
for (i = 1; i < len; i++) {
int price = prices[i];
for (j = 1; j <= k; j++) {
profit[j][0] = (profit[j][1]+price)>profit[j][0]?(profit[j][1]+price):profit[j][0];
profit[j][1] = (profit[j-1][0]-price)>profit[j][1]?(profit[j-1][0]-price):profit[j][1];
}
}
return profit[k][0];
}
};