LeetCode 309. Best Time to Buy and Sell Stock with Cooldown

cool down time: at least one day

//we use dp, and the following explaination is crystal clear
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75931/Easiest-JAVA-solution-with-explanations
class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) return 0;
        if(prices.length == 1) return 0;
        if(prices.length == 2) return Math.max(0, prices[1] - prices[0]);
        
        int m = prices.length;
        
        int[] buy = new int[m];
        int[] sell = new int[m];
        
        //buy[i] means: Maximum profit which end with buying on day i or end with buying on a day before i and takes rest until the day i since then.
        //sell[i] means: Maximum profit which end with selling on day i or end with selling on a day before i and takes rest until the day i since then.
        
        buy[0] = -prices[0]; //we choose to buy in day1, that will gives us the max profit which is -prince[0]
        sell[0] = 0;//we can't sell so the max profit will be 0
        //we have to write the transaction equations down before we consider what part of these dp array should we initialize
        buy[1] = -Math.min(prices[0], prices[1]);//we can either choose to buy on day2, but since we can't sold anything, the max profit will be the last one we are gonna pay
        sell[1] = Math.max(0, prices[1] - prices[0]); //we can buy on day1 and sold on day2. so we can find a larger one between those two.
        
        for (int i = 2; i < prices.length; i++) {
            buy[i] = Math.max(buy[i-1], sell[i-2] - prices[i]);
            sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]);
        }
        //the reason we didn't iterate all dp arrays to find a max is: prices[i] is not guaranteed to choose. so each time we get something it's a maximal so far
        return sell[prices.length - 1];
        
    }
}
posted @ 2020-11-21 10:10  EvanMeetTheWorld  阅读(23)  评论(0)    收藏  举报