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 }