188. Best Time to Buy and Sell Stock IV***
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
题目描述
Say you have an array for which the i-th
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.
C++ 实现 1
推荐文章: Most consistent ways of dealing with the series of stock problems.
关于交易次数 K
进行了限制, 代码实现参考: 123. Best Time to Buy and Sell Stock III*** 中的 C++ 实现 2
.
通用递推公式为:
Base cases:
T[-1][k][0] = 0, T[-1][k][1] = -Infinity
T[i][0][0] = 0, T[i][0][1] = -Infinity
Recurrence relations:
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i]) # sell
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i]) # buy
然而此题在实现时, 需要考虑到, 如果 K >= prices.size() / 2
, 即 K
特别大的时候, (之所以 prices.size()
要除以 2, 是因为每进行一个动作, 比如 buy
, 肯定要有对应的 sell
动作), 此时其实问题已经退化为, 在 prices
范围内进行无限次数的交易, 等同于 122. Best Time to Buy and Sell Stock II*.
class Solution {
public:
int maxProfit(int K, vector<int>& prices) {
int s0 = 0, s1 = INT32_MIN;
// 如果 K 特别大, 超过了 prices.size() / 2 (除以 2 是因为 buy and sell 需要
// 两个值), 此时 prices 的值不够了, 多余的 transaction 是没有意义的, 最大收益已经
// 固定了. 其实此时相当于在 prices 上进行 infinite transactions.
if (K >= prices.size() / 2) {
for (int i = 0; i < prices.size(); ++ i) {
int prev_s0 = s0;
s0 = std::max(s0, s1 + prices[i]); // sell
s1 = std::max(s1, prev_s0 - prices[i]); // buy
}
} else {
// 实际上, 不论 K 为多大, T 设置为 (2, prices.size() + 1) 的大小就行了
// 但为了理解方便, 就设置为 (K + 1, prices.size() + 1) 便于推广到 K != 2 的情况.
vector<vector<int>> T(2, vector<int>(prices.size() + 1, 0));
for (int k = 0; k < K; ++ k) {
s0 = 0, s1 = INT32_MIN;
for (int i = 0; i < prices.size(); ++ i) {
s0 = std::max(s0, s1 + prices[i]); // sell
s1 = std::max(s1, T[k % 2][i] - prices[i]); // buy
T[(k + 1) % 2][i + 1] = s0;
}
}
}
return s0;
}
};