From b2132c4a69a30fbf261195c6d78f42562a43ff46 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Fri, 5 Nov 2021 12:52:48 +0000 Subject: [PATCH] best-time-to-buy-and-sell-stock --- best-time-to-buy-and-sell-stock/sol.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/sol.go diff --git a/best-time-to-buy-and-sell-stock/sol.go b/best-time-to-buy-and-sell-stock/sol.go new file mode 100644 index 0000000..28fad5a --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sol.go @@ -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 +}