Skip to content

Commit cb57b7f

Browse files
committed
solve: best time to buy and sell stock
1 parent a5bcbc9 commit cb57b7f

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// time: O(n) space: O(n)
2+
class Solution {
3+
func maxProfit(_ prices: [Int]) -> Int {
4+
guard !prices.isEmpty else { return 0 }
5+
var result = [Int]()
6+
var current = prices[0]
7+
8+
for price in prices {
9+
if current > price {
10+
current = price
11+
continue
12+
}
13+
result.append(price - current)
14+
}
15+
return result.max() ?? 0
16+
}
17+
}

0 commit comments

Comments
 (0)