1552. Magnetic Force Between Two Balls

Question

CleanShot 2024-09-02 at 15.04.31@2x.png

Code

class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        position.sort()
        
        def canPlace(force):

            prev = position[0]
            numberPlaced = 1

            for i in range(1, len(position)):
                if position[i] - prev >= force:
                    numberPlaced += 1
                    prev = position[i]
            return numberPlaced >= m


        maxForce = position[-1] - position[0]

        l, r = 1, maxForce

        
        while l <= r:
            mid = l + (r - l) // 2
            if canPlace(mid):
                if mid == maxForce or not canPlace(mid + 1):
                    return mid
                else:
                    l = mid + 1
            else:
                r = mid - 1

        return l