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).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
思路
动态规划的方法来做,参考资料1的方法比较晦涩难懂,搜了一下,好像大部分都是采用这种方法来做的,放弃了。
找到了一个好懂一点的方法,学习一下:
类似最大连续和问题,我们需要变量来记录当前的一些状态信息,因为是k次交易,所以我们需要大小为k的数组记录每一次交易的信息,
又因为一次交易包含买和卖两次操作,所以我们需要两个数组。分别命名为hold【】和sell【】。
- hold[i]表示第i次持有后的盈亏,也就是第i次买入后的状态
- sell[i]表示第i次卖出后的盈亏状态
比如上个例子1,3,7,2,1,5.如果我们在第一天买入,那么hold[1]应该是-1,这里可能会问,为什么会是负数?那是因为我们买入了股票,钱已经花出去了,但我们还没有卖出,所以当前你手上是没有现金的,只有股票。
算法核心就是两句:
cur = prices[i];
sell[j] = std::max(sell[j], hold[j] + cur);
hold[j] = std::max(hold[j], sell[j-1] - cur);
在第i天第j次 卖出 的盈亏最大值为 已卖出 和 第j次持有并在第i天卖出 之间的最大值。
在第i天第j次 持有 的盈亏最大值为 继续持有 和 第j-1次卖出并在第i天又买入 之间的最大值。
c++11
如果k大于等于长度的一半,则说明可以任意次交易得到最大值。否则采用dp算法。
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if (k >= prices.size()/2) {
int res = 0;
for (int i = 1; i < prices.size(); i++)
if (prices[i] > prices[i-1])
res += std::max(prices[i] - prices[i-1], 0);
return res;
}
int hold[k+1];
int sell[k+1];
for (int i=0; i<=k; ++i){
hold[i] = INT_MIN;
sell[i] = 0;
}
for (int i = 0; i < prices.size(); i++) {
for (int j = 1; j <= k; j++) {
sell[j] = std::max(sell[j], hold[j] + prices[i]);
hold[j] = std::max(hold[j], sell[j-1] - prices[i]);
}
}
return sell[k];
}
};
AC结果:
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock IV.
Memory Usage: 9 MB, less than 61.68% of C++ online submissions for Best Time to Buy and Sell Stock IV.