Skip to content

Commit

Permalink
Improve soapyigu#121 Best Time to Buy and Sell Stock
Browse files Browse the repository at this point in the history
  • Loading branch information
ShawnMa16 committed May 2, 2019
1 parent 0f4b28c commit ac0d4ad
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions DP/BestTimeBuySellStock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@

class BestTimeBuySellStock {
func maxProfit(prices: [Int]) -> Int {
guard prices.count >= 2 else {
return 0
}

guard prices.count > 0 else {return 0}
var maxProfit = 0
var lowest = prices[0]
var buyDay = 0

for price in prices {
maxProfit = max(maxProfit, price - lowest)
lowest = min(lowest, price)
for i in 1 ..< prices.count {
let profit = prices[i] - prices[buyDay]
if profit < 0 {
buyDay = i
}
maxProfit = max(profit, maxProfit)
}

return maxProfit
Expand Down

0 comments on commit ac0d4ad

Please sign in to comment.