40 lines
729 B
Go
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
|
|
}
|