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 two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution {
public:
int maxProfit(vector<int> &prices) {
int hold1 = INT_MIN, hold2 = INT_MIN;
int release1 = 0, release2 = 0;
for (auto price : prices) {
release2 = max(release2, hold2 + price);
hold2 = max(hold2, release1 - price);
release1 = max(release1, hold1 + price);
hold1 = max(hold1, -price);
}
return release2;
}
};
算法介绍请参考下面网址:
https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1