go: add «1552. Magnetic Force Between Two Balls»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
d1e6ee86c5
commit
3ca391ca27
1 changed files with 41 additions and 0 deletions
41
go/magnetic-force-between-two-balls.go
Normal file
41
go/magnetic-force-between-two-balls.go
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "slices"
|
||||||
|
|
||||||
|
func maxDistance(position []int, m int) int {
|
||||||
|
placed := func(distance int) bool {
|
||||||
|
counter := 1
|
||||||
|
|
||||||
|
last := position[0]
|
||||||
|
for _, p := range position {
|
||||||
|
if p-last >= distance {
|
||||||
|
counter++
|
||||||
|
last = p
|
||||||
|
}
|
||||||
|
|
||||||
|
if counter >= m {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
slices.Sort(position)
|
||||||
|
|
||||||
|
low := 1
|
||||||
|
high := (position[len(position)-1] - position[0]) / (m - 1)
|
||||||
|
|
||||||
|
foundMax := 1
|
||||||
|
for low <= high {
|
||||||
|
mid := low + (high-low)/2
|
||||||
|
if placed(mid) {
|
||||||
|
foundMax = mid
|
||||||
|
low = mid + 1
|
||||||
|
} else {
|
||||||
|
high = mid - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return foundMax
|
||||||
|
}
|
Loading…
Reference in a new issue