lc-go/solutions/7/q714/solution.go

34 lines
849 B
Go

// Package q714 implements a solution for https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
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