LeetCode in Kotlin

1552. Magnetic Force Between Two Balls

Medium

In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

Given the integer array position and the integer m. Return the required force.

Example 1:

Input: position = [1,2,3,4,7], m = 3

Output: 3

Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.

Example 2:

Input: position = [5,4,3,2,1,1000000000], m = 2

Output: 999999999

Explanation: We can use baskets 1 and 1000000000.

Constraints:

Solution

class Solution {
    fun maxDistance(position: IntArray, m: Int): Int {
        position.sort()
        return binarySearch(position, m)
    }

    private fun binarySearch(arr: IntArray, m: Int): Int {
        var low = 0
        val n = arr.size
        var high = arr[n - 1]
        var max = -1
        while (low <= high) {
            val mid = low + (high - low) / 2
            if (check(arr, mid, m)) {
                if (max < mid) {
                    max = mid
                }
                low = mid + 1
            } else {
                high = mid - 1
            }
        }
        return max
    }

    private fun check(arr: IntArray, mid: Int, m: Int): Boolean {
        var pos = arr[0]
        var magnet = 1
        for (i in 1 until arr.size) {
            if (arr[i] - pos >= mid) {
                pos = arr[i]
                magnet += 1
                if (magnet == m) {
                    return true
                }
            }
        }
        return false
    }
}