go: add «1590. Make Sum Divisible by P»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9c8e14695c
commit
5e5928bd8a
1 changed files with 40 additions and 0 deletions
40
go/make-sum-divisible-by-p.go
Normal file
40
go/make-sum-divisible-by-p.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue