Advertisement
bayareabelletrist

Most Profit from Stock Prices with Cooldown

Jul 30th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @interface Solution: NSObject
  2. -(int)mostProfitFromStockPricesWithCooldown:(NSArray<NSNumber *> *)prices;
  3. @end
  4.  
  5. @implementation Solution
  6. -(int)mostProfitFromStockPricesWithCooldown:(NSArray<NSNumber *> *)prices {
  7.     int haveStockPlusOne = 0;
  8.     int haveStockPlusTwo = 0;
  9.     int noStockPlusOne = 0;
  10.     int noStockPlusTwo = 0;
  11.  
  12.     for(int i = (int)prices.count-1; i >= 0; i--) {
  13.         int buyHere = -prices[i].intValue + haveStockPlusOne;
  14.         int sellHere = prices[i].intValue + noStockPlusTwo;
  15.         int holdStock = haveStockPlusOne;
  16.         int keepDoingNothing = noStockPlusOne;
  17.        
  18.         int haveStock = MAX(sellHere, holdStock);
  19.         int noStock = MAX(buyHere, keepDoingNothing);
  20.        
  21.         noStockPlusTwo = noStockPlusOne;
  22.         noStockPlusOne = noStock;
  23.         haveStockPlusTwo = haveStockPlusOne;
  24.         haveStockPlusOne = haveStock;
  25.     }
  26.    
  27.     int buyFirst = -prices[0].intValue + haveStockPlusTwo;
  28.     int skipFirst = noStockPlusOne;
  29.     return MAX(buyFirst, skipFirst);
  30. }
  31. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement