best-time-to-buy-and-sell-stock-ii
This commit is contained in:
parent
672c13b219
commit
a9f0806793
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue