From 59f2aedce547f5acd57808a8d304e4f9f3f58ffc Mon Sep 17 00:00:00 2001 From: Invidam Date: Tue, 30 Apr 2024 19:21:35 +0900 Subject: [PATCH] best-time-to-buy-and-sell-stock: use greedy algorithm --- best-time-to-buy-and-sell-stock/invidam.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/best-time-to-buy-and-sell-stock/invidam.go b/best-time-to-buy-and-sell-stock/invidam.go index 35185a3a3..55671947e 100644 --- a/best-time-to-buy-and-sell-stock/invidam.go +++ b/best-time-to-buy-and-sell-stock/invidam.go @@ -1,12 +1,10 @@ func maxProfit(prices []int) int { - maxPriceFrom := make([]int, len(prices)+1) - for i := len(prices) - 1; i >= 0; i-- { - maxPriceFrom[i] = max(maxPriceFrom[i+1], prices[i]) - } + purchasePrice := prices[0] + maxBenefit := 0 - maxPriceDiff := 0 - for i, price := range prices { - maxPriceDiff = max(maxPriceDiff, maxPriceFrom[i+1]-price) + for _, price := range prices { + purchasePrice = min(purchasePrice, price) + maxBenefit = max(maxBenefit, price-purchasePrice) } - return maxPriceDiff + return maxBenefit }