1919 * Output: 3
2020 * Explanation: transactions = [buy, sell, cooldown, buy, sell]
2121 ******************************************************************************************************/
22-
2322class Solution {
2423public:
2524 //
@@ -32,47 +31,33 @@ class Solution {
3231 // Also set sell[0] = 0, that you do nothing in the first day.
3332 //
3433 // So,
35- //
36- // sell[i] = max ( buy[i-1] + prices[i],
37- // sell[i-1] - prices[i-1] + prices[i] );
38- //
39- // - buy[i-1]+prices[i] represents buy the stock on day i-1 and sell it on day i;
40- // - sell[i-1]-prices[i-1]+prices[i] represents you didn't sell the stock on day i-1
41- // but sell it on day i (bought stock back and sell it on day i).
42- //
43- //
44- // buy[i] = max ( sell[i-2] - prices[i],
45- // buy[i-1] + prices[i-1] - prices[i] );
46- //
47- // - sell[i-2]-prices[i] means sold the stock on day i-2 and buy it on day i
48- // (day i-1 is cooldown).
49- // - buy[i-1]+prices[i-1]-prices[i] means you didn't buy the stock on day i-1
50- // but buy it on day i.
51- //
52-
34+ // buy[i] = max(buy[i-1], // do nothing - keep holding
35+ // sell[i-2] - prices[i] ) // sell previous day, buy today
36+ // // i-1 is cooldown day
37+ // sell[i] = max(sell[i-1], // do nothing
38+ // buy[i-1] + prices[i] ) // buy previous day, sell today.
39+ //
40+
5341 int maxProfit (vector<int >& prices) {
5442 int len = prices.size ();
5543 if ( len < 2 ) return 0 ;
44+
5645 vector<int > buy (len, 0 );
5746 vector<int > sell (len, 0 );
5847
48+ // day 0
5949 buy[0 ] = -prices[0 ];
50+ sell[0 ] = 0 ;
6051
61- int profit = 0 ;
52+ // day 1
53+ buy[1 ] = max (buy[0 ], 0 - prices[1 ]);
54+ sell[1 ] = max (sell[0 ], buy[0 ] + prices[1 ]);
6255
63- for (int i=1 ; i<len; i++) {
64- sell[i] = max ( buy[i-1 ] + prices[i],
65- sell[i-1 ] - prices[i-1 ] + prices[i] );
66- profit = max (profit, sell[i]);
67- if ( i == 1 ) {
68- buy[i] = buy[0 ] + prices[0 ] - prices[1 ];
69- } else {
70- buy[i] = max ( sell[i-2 ] - prices[i],
71- buy[i-1 ] + prices[i-1 ] - prices[i] );
72- }
73-
56+ for (int i=2 ; i<len; i++) {
57+ buy[i] = max ( buy[i - 1 ], sell[i - 2 ] - prices[i]);
58+ sell[i] = max (sell[i - 1 ], buy[i - 1 ] + prices[i]);
7459 }
7560
76- return profit ;
61+ return sell[len- 1 ] ;
7762 }
7863};
0 commit comments