best-time-to-buy-and-sell-stock

This commit is contained in:
Gleb Koval 2021-11-05 12:52:48 +00:00
parent 8c338a768f
commit b2132c4a69
No known key found for this signature in database
GPG Key ID: 7C89CDC822F8392B
1 changed files with 15 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package main
// Time: O(n)
// Space: O(1)
func maxProfit(prices []int) int {
min, max := prices[0], 0
for _, price := range prices {
if price < min {
min = price
} else if diff := price - min; diff > max {
max = diff
}
}
return max
}