We recast the problem of maximizing the minimum force into the problem: Given the sequence of minimum forces , what is the rightmost value that is achievable. To search the rightmost value, we perform binary search in the range [1,
]. In each iteration of the binary-search, we check, for a given value of minimum force, all
balls can be placed. To make that check efficient we also sort
position.
Time: , space: that of sorting.
class Solution:
def can_place(self, position, m, min_force) -> bool:
prev, curr = 0, 1
m = m-1
while curr < len(position) and m > 0:
if abs( position[prev] - position[curr] ) < min_force:
curr += 1
continue
m -= 1
prev = curr
curr += 1
return m == 0
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
lo, hi = 1, position[-1] - position[0]
force = 1
while lo <= hi:
mid = (lo + hi) // 2
if self.can_place(position, m, mid):
force = mid
lo = mid+1
else:
hi = mid-1
return force
Leave a comment