We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0f4b28c commit ac0d4adCopy full SHA for ac0d4ad
DP/BestTimeBuySellStock.swift
@@ -8,16 +8,16 @@
8
9
class BestTimeBuySellStock {
10
func maxProfit(prices: [Int]) -> Int {
11
- guard prices.count >= 2 else {
12
- return 0
13
- }
14
-
+ guard prices.count > 0 else {return 0}
15
var maxProfit = 0
16
- var lowest = prices[0]
+ var buyDay = 0
17
18
- for price in prices {
19
- maxProfit = max(maxProfit, price - lowest)
20
- 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)
21
}
22
23
return maxProfit
0 commit comments