24 lines
397 B
Go
24 lines
397 B
Go
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
|
|
}
|