Program to maximize the minimum force between balls in a bucket using Python

Suppose we are given several buckets and x number of balls. If the balls are put into the bucket, a special force acts within them and we have to find out a way to maximize the minimum force between two balls. The force between two balls in a bucket of position p and q is |p - q|. The input given to us is the array containing the bucket positions and the number of balls x. We have to find out the minimum force between them.

So, if the input is like pos = [2, 4, 6, 8, 10, 12], x = 3, then the output will be 4.

2 4 6 8 10 12 4 4 Optimal placement: positions 4, 8, 12 Minimum force between balls = 4

The balls can be put into the given positions in an array of 12 buckets. The three balls can be put into positions 4, 8, and 12 and the power between them will be 4. This value cannot be increased further.

Algorithm Approach

This problem can be solved using binary search on the answer. We use a helper function to count how many balls can be placed with a given minimum distance.

To solve this, we will follow these steps −

  • Define a function ball_count(). This will take d

    • ans := 1

    • curr := pos[0]

    • for i in range 1 to n, do

      • if pos[i] - curr >= d, then

        • ans := ans + 1

        • curr := pos[i]

    • return ans

  • n := size of pos

  • sort the list pos

  • left := 0

  • right := pos[-1] - pos[0]

  • while left

    • mid := right - floor value of((right - left) / 2)

    • if ball_count(mid) >= x, then

      • left := mid

    • otherwise,

      • right := mid - 1

  • return left

Example

Let us see the following implementation to get better understanding −

def solve(pos, x):
    n = len(pos)
    pos.sort()

    def ball_count(d):
        ans, curr = 1, pos[0]
        for i in range(1, n):
            if pos[i] - curr >= d:
                ans += 1
                curr = pos[i]
        return ans

    left, right = 0, pos[-1] - pos[0]
    while left < right:
        mid = right - (right - left) // 2
        if ball_count(mid) >= x:
            left = mid
        else:
            right = mid - 1
    return left

print(solve([2, 4, 6, 8, 10, 12], 3))

The output of the above code is −

4

How It Works

The algorithm uses binary search to find the maximum possible minimum distance. The ball_count() function checks if we can place at least x balls with a given minimum distance d. We start with the first position and greedily place balls whenever the distance constraint is satisfied.

Conclusion

This problem demonstrates the use of binary search on answer technique. By checking if a certain minimum distance is achievable and adjusting our search range accordingly, we can efficiently find the maximum minimum force between balls.

Updated on: 2026-03-26T13:55:33+05:30

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements