123. 买卖股票的最佳时机 III

 1 class Solution 
 2 {
 3 public:
 4     int maxProfit(vector<int>& prices) 
 5     {
 6         if(prices.empty()) return 0;
 7         int n = prices.size();
 8         vector<vector<vector<int>>> dp(n,vector<vector<int>>(3,vector<int>(2,0)));
 9 
10         for(int k = 1;k <= 2;k ++)
11         {
12             dp[0][k][0] = 0;
13             dp[0][k][1] = -prices[0];
14         }
15 
16         for(int i = 1;i < n;i ++)
17         {
18             for(int k = 1;k <= 2;k ++)
19             {
20                 dp[i][k][0] = max(dp[i-1][k][0],dp[i-1][k][1] + prices[i]);
21                 dp[i][k][1] = max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i]);
22             }
23         }
24 
25         return max(dp[n-1][1][0],dp[n-1][2][0]);
26     }
27 };

 

上一篇:git的小命令


下一篇:Todo List