[go: nahoru, domu]

Skip to content

Commit

Permalink
Submit 309_BestTimetoBuyandSellStockwithCooldown
Browse files Browse the repository at this point in the history
  • Loading branch information
Binlogo committed Jul 10, 2020
1 parent 18e5f2a commit 0344720
Showing 1 changed file with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//: [Previous](@previous)

import Foundation

class Solution {
func maxProfit(_ prices: [Int]) -> Int {
guard !prices.isEmpty else { return 0 }
var rest = 0
var sold = 0
var hold = Int.min
for current in 0..<prices.count {
let currentPrice = prices[current]
let preSold = sold
let preHold = hold
hold = max(preHold, rest - currentPrice)
sold = preHold + currentPrice
rest = max(rest, preSold)
}
return max(rest, sold)
}
}

// Tests
let s = Solution()
s.maxProfit([1,2,3,0,2]) == 3

//: [Next](@next)

0 comments on commit 0344720

Please sign in to comment.