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).
这题要结合121,122题来一起思考。这一题和121的要求差不多,但是最多只能进行两次的操作,就最多可以买入卖出两次,同时必须先买入才能卖出,然后问最大利润是多少。这一题用贪心就做不了了,需要用到动态规划,其中设f[i]表示区间[0,i]之间的最大利润,设g[i]表示区间[i,n-1]之间的最大利润。所以结果就是max{f[i] + g[i]},用三个循环就可以解决,那么时间和空间复杂度是O(n),代码如下。
Code(LeetCode运行9ms):
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n < 2) {
return 0;
}
vector<int> f(n, 0); //f[i]表示[0,i]的最大利润.
vector<int> g(n, 0); //g[i]表示[i, n-1]的最大利润
for (int i = 1, Min = prices[0]; i < n; i++) {
Min = min(Min, prices[i]);
f[i] = max(f[i - 1], prices[i] - Min);
}
for (int i = n - 2, Max = prices[n - 1]; i >= 0; i--) {
Max = max(Max, prices[i]);
g[i] = max(g[i - 1], Max - prices[i]);
}
int result = 0;
for (int i = 0; i < n; i++) {
result = max(result, f[i] + g[i]);
}
return result;
}
};