Skip to content

Commit ac0d4ad

Browse files
committed
Improve #121 Best Time to Buy and Sell Stock
1 parent 0f4b28c commit ac0d4ad

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

DP/BestTimeBuySellStock.swift

+8-8
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@
88

99
class BestTimeBuySellStock {
1010
func maxProfit(prices: [Int]) -> Int {
11-
guard prices.count >= 2 else {
12-
return 0
13-
}
14-
11+
guard prices.count > 0 else {return 0}
1512
var maxProfit = 0
16-
var lowest = prices[0]
13+
var buyDay = 0
1714

18-
for price in prices {
19-
maxProfit = max(maxProfit, price - lowest)
20-
lowest = min(lowest, price)
15+
for i in 1 ..< prices.count {
16+
let profit = prices[i] - prices[buyDay]
17+
if profit < 0 {
18+
buyDay = i
19+
}
20+
maxProfit = max(profit, maxProfit)
2121
}
2222

2323
return maxProfit

0 commit comments

Comments
 (0)