Advertisement
1988coder

309. Best Time to Buy and Sell Stock with Cooldown

Dec 30th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. /**
  2.  * Refer: 1)
  3.  * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75927/Share-my-thinking-process/173646
  4.  * 2)
  5.  * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75927/Share-my-thinking-process
  6.  *
  7.  * On any i-th day, we can buy, sell or cooldown
  8.  *
  9.  * To calculate sell[i]: If we sell on the i-th day, the maximum profit is buy[i
  10.  * - 1] + price, because we have to buy before we can sell. If we cooldown on
  11.  * the i-th day, the maximum profit is same as sell[i - 1] since we did nothing
  12.  * on the i-th day. So sell[i] is the larger one of (buy[i - 1] + price, sell[i
  13.  * - 1])
  14.  *
  15.  * To calculate buy[i]: If we buy on the i-th day, the maximum profit is sell[i
  16.  * - 2] - price, because on the (i-1)th day we can only cooldown. If we cooldown
  17.  * on the i-th day, the maximum profit is same as buy[i - 1] since we did
  18.  * nothing on the i-th day. So buy[i] is the larger one of (sell[i - 2] - price,
  19.  * buy[i - 1])
  20.  *
  21.  * Time Complexity: O(N). Space Complexity: O(1)
  22.  *
  23.  * N = Length of input prices array.
  24.  */
  25. class Solution {
  26.     public int maxProfit(int[] prices) {
  27.         if (prices == null || prices.length <= 1) {
  28.             return 0;
  29.         }
  30.  
  31.         int sell = 0;
  32.         int prevSell = 0;
  33.         int buy = Integer.MIN_VALUE;
  34.         int prevBuy = Integer.MIN_VALUE;
  35.  
  36.         for (int price : prices) {
  37.             // buy[i-1]
  38.             prevBuy = buy;
  39.  
  40.             // buy[i] = Math.max(sell[i-2]-price[i], buy[i-1])
  41.             // sell[i-2]-price[i] -> Buy after a 1 day cooldown
  42.             // buy[i-1] -> cooldown
  43.             buy = Math.max(prevSell - price, prevBuy);
  44.  
  45.             // sell[i-1];
  46.             prevSell = sell;
  47.  
  48.             // sell[i] = Math.max(buy[i-1]+price, sell[i-1])
  49.             // buy[i-1]+price -> sell the stock.
  50.             // sell[i-1] -> dcooldown
  51.             sell = Math.max(prevBuy + price, prevSell);
  52.         }
  53.  
  54.         return sell;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement