Files
leetcode/2398-max-num-robots-on-budget.go
2023-01-04 23:14:28 +02:00

131 lines
2.2 KiB
Go

package main
import (
"fmt"
"math"
)
func minInt(in []int) int {
m := math.MaxInt
for _, v := range in {
if v < m {
m = v
}
}
return m
}
func maxInt(in []int, start int, end int) (int, int) {
fmt.Println(start, " - ", end)
m := math.MinInt
place := -1
for i := start; i <= end; i++ {
v := in[i]
if v > m {
place = i
m = v
}
}
return m, place
}
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
}
key.end++
value, ok = maxIntCache[key]
if !ok {
maxValue, _ := maxInt(in, start, end)
value = maxValue
key.start = start
key.end = end
maxIntCache[key] = value
} else {
if value == in[end+1] {
maxValue, _ := maxInt(in, start, end)
value = maxValue
key.start = start
key.end = end
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 {
maxIntCache = map[CacheKey]int{}
l := len(chargeTimes)
if l != len(runningCosts) {
return 0
}
maxCharge := maxIntCached(chargeTimes, 0, l-1)
//minCosts := minInt(runningCosts)
//if int64(maxCharge + minCosts) > budget {
//return 0
//}
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
}