Magnetic Force Between Two Balls LeetCode

 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.

 


class Solution {
    public int maxDistance(int[] position, int m) {
       
           // Step 1: Sort the input array (basket positions)
        Arrays.sort(position);
        int n = position.length;

        // Step 2: Define the search space for binary search
        int start = 1; // Minimum possible magnetic force
        int end = position[n - 1] - position[0]; // Maximum possible magnetic force (max distance between two ends)
        int ans = 0; // Store the best answer

        // Step 3: Binary search for the maximum minimum force
        while (start <= end) {
            int mid = start + (end - start) / 2; // Try this as the minimum distance

            int ballcount = 1; // Place the first ball at the first position
            int ballposition = position[0]; // The position of the last placed ball

            // Step 4: Try placing remaining balls greedily
            for (int i = 1; i < n; i++) {
                // If current position is far enough from the last ball's position
                if (position[i] >= ballposition + mid) {
                    ballcount++; // Place the ball
                    ballposition = position[i]; // Update last ball position
                }
            }

            // Step 5: Check if we could place at least m balls
            if (ballcount < m) {
                end = mid - 1; // Distance too big, reduce it
            } else {
                ans = mid; // Distance is valid, try for bigger one
                start = mid + 1;
            }
        }

        // Step 6: Return the maximum minimum distance found
        return ans;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence