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

This commit is contained in:
Gleb Koval 2021-11-10 14:44:37 +00:00
parent 672c13b219
commit a9f0806793
No known key found for this signature in database
GPG Key ID: DF27F6A77C48FDA0
1 changed files with 23 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package main
// Time: O(n)
// Space: O(1)
func maxProfit(prices []int) int {
l := len(prices)
sum, start, last, lock := 0, 0, prices[0], false
for i := range prices {
last = prices[i]
if !lock {
if i >= l-1 || prices[i+1] > last {
start = last
lock = true
}
} else {
if i >= l-1 || prices[i+1] < last {
sum += last - start
lock = false
}
}
}
return sum
}