1+ class Solution (object ):
2+ def maxProfit (self , prices ):
3+ if not prices or len (prices )<= 1 : return 0
4+ N = len (prices )
5+
6+ buy = [- prices [0 ], max (- prices [1 ], - prices [0 ])]
7+ sell = [0 , max (prices [1 ]+ buy [0 ], 0 )]
8+
9+ for i in xrange (2 , N ):
10+ buy .append (max (sell [i - 2 ]- prices [i ], buy [i - 1 ]))
11+ sell .append (max (prices [i ]+ buy [i - 1 ], sell [i - 1 ]))
12+
13+ return max (buy [- 1 ], sell [- 1 ], 0 )
14+
15+ """
16+ Three rules:
17+ 1. Need to buy before sell.
18+ 2. After sell, next day need to rest (cannot buy).
19+ 3. When buying, we spend money, which is a negative profit.
20+
21+ There are two possible end state. buy or sell. So we need to consider both.
22+ Only considering prices 0~i, buy[i] stores the max profit that the last action is "buy".
23+ Only considering prices 0~i, sell[i] stores the max profit that the last action is "sell".
24+
25+ Let's sort this out.
26+ When i==0:
27+ buy: -prices[0]
28+ sell: 0, since we cannot sell at i==0.
29+
30+ When i==1:
31+ buy: max(-prices[1], -prices[0])
32+ Now, we must not have sell yet. So no need to consider it.
33+ If we buy at i==1, the profit will be `-prices[1]`. But we also had the option not to buy. buy[0] is the max profit if we don't buy at i==1.
34+ Again, we are considering, when the end state is "buy", what is the max profit?
35+ Thus, `max(-prices[1], buy[0])`.
36+
37+ sell: max(prices[1]+buy[0], 0)
38+ If we sell at i==1, the profit will be `prices[1]+buy[0]`. But we also had the option not to sell. 0 is the max profit if we don't sell at i==1.
39+ Again, we are considering, when the end state is "sell", what is the max profit?
40+ Thus, `max(prices[1]+buy[0], sell[0])`
41+
42+ When i>=2:
43+
44+
45+
46+
47+ """
0 commit comments