yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #309. Best Time to Buy and Sell Stock with Cooldown #254

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int maxProfit(int[] prices) {
    if(prices == null || prices.length <= 1) return 0;

    int b0 = -prices[0], b1 = b0;
    int s0 = 0, s1 = 0, s2 = 0;

    for(int i = 1; i < prices.length; i++) {
        b0 = Math.max(b1, s2 - prices[i]);
        s0 = Math.max(s1, b1 + prices[i]);
        b1 = b0; s2 = s1; s1 = s0; 
    }
    return s0;
}
}

This is such a genius solution by:

  1. Derive the recursive solution by dividing it to four cases (buy or not at i, sell or not at i)
  2. Achieve O(1) space complexity by storing the values in int.

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75931/Easiest-JAVA-solution-with-explanations