From a9f0806793c8e765a8e5c632370f28dc192ca4b7 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Wed, 10 Nov 2021 14:44:37 +0000 Subject: [PATCH] best-time-to-buy-and-sell-stock-ii --- best-time-to-buy-and-sell-stock-ii/sol.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock-ii/sol.go diff --git a/best-time-to-buy-and-sell-stock-ii/sol.go b/best-time-to-buy-and-sell-stock-ii/sol.go new file mode 100644 index 0000000..bcce919 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-ii/sol.go @@ -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 +}