Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @interface Solution: NSObject
- -(int)mostProfitFromStockPricesWithCooldown:(NSArray<NSNumber *> *)prices;
- @end
- @implementation Solution
- -(int)mostProfitFromStockPricesWithCooldown:(NSArray<NSNumber *> *)prices {
- int haveStockPlusOne = 0;
- int haveStockPlusTwo = 0;
- int noStockPlusOne = 0;
- int noStockPlusTwo = 0;
- for(int i = (int)prices.count-1; i >= 0; i--) {
- int buyHere = -prices[i].intValue + haveStockPlusOne;
- int sellHere = prices[i].intValue + noStockPlusTwo;
- int holdStock = haveStockPlusOne;
- int keepDoingNothing = noStockPlusOne;
- int haveStock = MAX(sellHere, holdStock);
- int noStock = MAX(buyHere, keepDoingNothing);
- noStockPlusTwo = noStockPlusOne;
- noStockPlusOne = noStock;
- haveStockPlusTwo = haveStockPlusOne;
- haveStockPlusOne = haveStock;
- }
- int buyFirst = -prices[0].intValue + haveStockPlusTwo;
- int skipFirst = noStockPlusOne;
- return MAX(buyFirst, skipFirst);
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement