1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-10-18 14:52:09 +02:00
LeetCode/go/make-sum-divisible-by-p.go

41 lines
729 B
Go
Raw Normal View History

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
}