add new solutions
This commit is contained in:
parent
886b5e0a8e
commit
67cad91898
47 changed files with 1549 additions and 1 deletions
33
solutions/7/q714/solution.go
Normal file
33
solutions/7/q714/solution.go
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue