Files
leetcode/2398-max-num-robots-on-budget.go
2023-01-05 19:59:59 +02:00

91 lines
1.6 KiB
Go

package main
import "fmt"
type CacheKey struct {
start int
end int
}
var maxIntCache map[CacheKey]int
func maxIntCached(in []int, start int, end int) int {
key := CacheKey{start: start, end: end}
value, ok := maxIntCache[key]
if ok {
return value
}
fmt.Println(start, " - ", end)
key.start = start
value = in[start]
for j := start + 1; j <= end; j++ {
key.end = j
if in[j] > value {
value = in[j]
}
maxIntCache[key] = value
}
return value
}
func sumInt(in []int, start int, end int) int64 {
r := int64(0)
for i := start; i <= end; i++ {
r += int64(in[i])
}
return r
}
func MaximumRobots(chargeTimes []int, runningCosts []int, budget int64) int {
l := len(chargeTimes)
if l != len(runningCosts) {
return 0
}
maxIntCache = map[CacheKey]int{}
totalCost := sumInt(runningCosts, 0, l-1)
runCost := totalCost
for w := l; w > 0; w-- {
maxCharge := maxIntCached(chargeTimes, 0, w-1)
if w != l {
totalCost -= int64(runningCosts[w])
runCost = totalCost
}
if (int64(w)*runCost + int64(maxCharge)) <= budget {
return w
}
for s := 1; (s + w) <= l; s++ {
runCost -= int64(runningCosts[s-1])
runCost += int64(runningCosts[s+w-1])
if chargeTimes[s-1] == maxCharge {
if chargeTimes[s] != maxCharge {
maxCharge = maxIntCached(chargeTimes, s, s+w-1)
} else {
if chargeTimes[s+w-1] > maxCharge {
maxCharge = chargeTimes[s+w-1]
}
}
} else {
if chargeTimes[s+w-1] > maxCharge {
maxCharge = chargeTimes[s+w-1]
}
}
if (int64(w)*runCost + int64(maxCharge)) <= budget {
return w
}
}
}
return 0
}