go: add «1590. Make Sum Divisible by P»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-03 21:53:00 +02:00
parent 9c8e14695c
commit 5e5928bd8a
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,40 @@
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
}