add new solutions

This commit is contained in:
kanna5 2026-01-05 16:48:03 +09:00
parent 886b5e0a8e
commit 67cad91898
Signed by: kkyy
GPG key ID: 06332F3965E9B0CF
47 changed files with 1549 additions and 1 deletions

View file

@ -0,0 +1,33 @@
package q714
// Note: could be done faster with dynamic programming
func maxProfit(prices []int, fee int) int {
var low, high, profit int
bought := false
for i := range prices {
if bought {
high = max(high, prices[i])
if high-prices[i] > fee { // should have sold earlier or not bought
if high-low > fee {
profit += high - low - fee
}
bought = false
} else if prices[i] < low { // regret buying too early
low, high = prices[i], prices[i]
}
}
if !bought && i < len(prices)-1 && prices[i+1] > prices[i] {
bought = true // buy the dip
low, high = prices[i], prices[i]
}
}
if bought && high-low > fee {
profit += high - low - fee
}
return profit
}
var _ = maxProfit