Skip to content

Commit

Permalink
best-time-to-buy-and-sell-stock: use greedy algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Invidam committed Apr 30, 2024
1 parent 8678b9a commit 59f2aed
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions best-time-to-buy-and-sell-stock/invidam.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 59f2aed

Please sign in to comment.