13 lines easy to understand C++ solution, O(n) time, O(1) space


  • 0
    L
    int maxProfit(vector<int>& prices){
      int maxProfitsWhenBuyOrCooldown = 0;
      int maxProfitsWhenSellOrCooldown = 0;
      int maxProfitsWhenMustCooldown = 0;
      int tmp;
      for(int i = prices.size()-1; i >= 0; i --){
        tmp = maxProfitsWhenBuyOrCooldown;
        maxProfitsWhenBuyOrCooldown = max(-prices[i] + maxProfitsWhenSellOrCooldown, maxProfitsWhenBuyOrCooldown);
        maxProfitsWhenSellOrCooldown = max(prices[i] + maxProfitsWhenMustCooldown, maxProfitsWhenSellOrCooldown);
        maxProfitsWhenMustCooldown = tmp;
      }
      return maxProfitsWhenBuyOrCooldown;
    }
    

  • 0

    Just want to say... your variable names are really refreshing..


  • 0
    C

    Really great idea


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.