标签:time status one until sel 要求 mat fit mos
核心:按照状态:
一开始持有金额:0
由于从4->1向前依赖,所以对于每个i,赋值顺序应为4,3,2,1
而题目要求算出【第二次卖出】(即4)后的最大值,则有
4. sol2 = max(sol2, buy2+price[i]) -> 则需要buy2也最大,则需要求:
3. buy2 = max(buy2, sol1-price[i]) -> 则需要sol1也最大,则需要求:
2. sol1 = max(sol1, buy1+price[i]) -> 则需要buy1也最大,则需要求:
1. buy1 = max(buy1, -price[i])
参考代码:
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int buy1_status=INT_MIN, buy2_status=INT_MIN; 5 int profit1=0, profit2=0; 6 for(int i=0; i<prices.size(); i++){ 7 profit2=max(profit2, buy2_status+prices[i]); 8 buy2_status=max(profit1-prices[i], buy2_status); 9 profit1=max(profit1, buy1_status+prices[i]); 10 buy1_status=max(-prices[i], buy1_status); 11 } 12 return profit2; 13 } 14 15 };
方法2,动态规划
f[k][i]:共交易k次,在第i天交易所得最大收益。
边界值:
f[k][0]:共交易k次,在第0天交易所得最大收益为:0(第0天卖出的话,来不及买入,没有买入,何来卖出)
f[0][i]:共交易0次,在第i天交易所得最大收益为:0(没有交易)
转移方程:
★tmpMax
总共k次交易的时候,
每一天的最大收益=
或者
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions. 5 // f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] } 6 // = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj])) 7 // f[0, ii] = 0; 0 times transation makes 0 profit 8 // 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 9 if (prices.size() <= 1) return 0; 10 else { 11 int K = 2; // number of max transation allowed 12 int maxProf = 0; 13 vector<vector<int>> f(K+1, vector<int>(prices.size(), 0)); 14 for (int kk = 1; kk <= K; kk++) { 15 int tmpMax = f[kk-1][0] - prices[0]; 16 for (int ii = 1; ii < prices.size(); ii++) { 17 f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax); 18 tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]); 19 maxProf = max(f[kk][ii], maxProf); 20 } 21 } 22 return maxProf; 23 } 24 } 25 };
123. Best Time to Buy and Sell Stock III
标签:time status one until sel 要求 mat fit mos
原文地址:https://www.cnblogs.com/habibah-chang/p/12349569.html