Skip to content

Commit 59f2aed

Browse files
committed
best-time-to-buy-and-sell-stock: use greedy algorithm
1 parent 8678b9a commit 59f2aed

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed
Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
func maxProfit(prices []int) int {
2-
maxPriceFrom := make([]int, len(prices)+1)
3-
for i := len(prices) - 1; i >= 0; i-- {
4-
maxPriceFrom[i] = max(maxPriceFrom[i+1], prices[i])
5-
}
2+
purchasePrice := prices[0]
3+
maxBenefit := 0
64

7-
maxPriceDiff := 0
8-
for i, price := range prices {
9-
maxPriceDiff = max(maxPriceDiff, maxPriceFrom[i+1]-price)
5+
for _, price := range prices {
6+
purchasePrice = min(purchasePrice, price)
7+
maxBenefit = max(maxBenefit, price-purchasePrice)
108
}
11-
return maxPriceDiff
9+
return maxBenefit
1210
}

0 commit comments

Comments
 (0)