LeetCode/go/make-sum-divisible-by-p.go
Matej Focko 5e5928bd8a
go: add «1590. Make Sum Divisible by P»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-10-03 21:53:00 +02:00

40 lines
729 B
Go

package main
func minSubarray(nums []int, p int) int {
getTotalRemainder := func() int {
total := 0
for _, x := range nums {
total = (total + x) % p
}
return total
}
target := getTotalRemainder()
// whole array is divisible by p
if target == 0 {
return 0
}
mods := make(map[int]int)
mods[0] = -1
runningRemainder, foundMinimum := 0, len(nums)
for i, x := range nums {
runningRemainder = (runningRemainder + x) % p
complement := (runningRemainder + p - target) % p
length, found := mods[complement]
if found {
foundMinimum = min(foundMinimum, i-length)
}
mods[runningRemainder] = i
}
// didn't find any solution
if foundMinimum == len(nums) {
return -1
}
return foundMinimum
}