Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * hold: the money status when holding the stock.
 * sold: the money status after selling the stock.
 * cool: the money status when cooldown.
 */
class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        
        int hold = -prices[0], sold = 0, cool = 0;
        for (int price:prices) {
            int pre_hold = hold; // memorize hold in previous day to calculate the sold today.
            hold = Math.max(hold, cool - price);
            cool = sold; // cool equals sold in previous day as no action when cooldown.
            sold = Math.max(sold, pre_hold + price);
        }
        return sold;
    }
}