## 股票买卖最大收益总结-Best Time to Buy and Sell Stock

1. Best Time to Buy and Sell Stock III

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 (i.e., you must sell the stock before you buy again).

``````class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<=1) return 0;

vector<int> f(n,0),g(n,0);
int temp = INT_MAX,cur_max = 0;
//f[i]为前i个股票最多只买卖一次能够获得最大收益
for(int i=0;i<n;++i) {
temp = min(temp,prices[i]);
f[i] = max(cur_max,prices[i]-temp);
cur_max = f[i];
}
temp = 0;
cur_max = 0;
//g[i]为后n-i个股票最多只买卖一次能够获得的最大收益
for(int i=n-1;i>=0;--i) {
temp = max(temp,prices[i]);
g[i] = max(cur_max,temp - prices[i]);
cur_max = g[i];
}
//总的收益是所有可能选择的2分段的最大值
int res = 0;
for(int i=0;i<n;++i) {
res = max(res,g[i]+f[i]);
}
return res;
}
};
``````

g[i] = max(prices[k] - temp, g[i-1])

dp(i) = max(dp(i-1), prices[i] - m[i-1]) ，m[i-1]为0…i-1区间的最小值。
m[i] = min(prices[i], m[i-1])

``````def dp(i,prices,m):
if i == 0:
m[i] = prices[0]
return 0

cur = max(dp(i-1,prices,m),prices[i] - m[i-1])
m[i] = min(prices[i], m[i-1])
return cur
``````

``````class Solution {
public:
int maxProfit(vector<int> &prices) {
// f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions.
// f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
//          = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))
// f[0, ii] = 0; 0 times transation makes 0 profit
// f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade
if (prices.size() <= 1) return 0;
else {
int K = 2; // number of max transation allowed
int maxProf = 0;
vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
for (int kk = 1; kk <= K; kk++) {
int tmpMax = f[kk-1][0] - prices[0];
for (int ii = 1; ii < prices.size(); ii++) {
f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
maxProf = max(f[kk][ii], maxProf);
}
}
return maxProf;
}
}
};

``````