Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Magnetic Force Between Two Balls

Medium Acceptance 60% Points 30

You are given an integer array position[] representing the positions of balls on a number line and an integer m representing the number of balls to place. You must place exactly m balls in the given positions. The magnetic force between two balls is defined as the absolute distance between their positions. Your task is to place the balls such that the minimum magnetic force between any two balls is maximized. Return the maximum possible minimum magnetic force.

Examples
Example 1

Example 1

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

Output: 3

Explanation: The balls can be placed at positions 1, 4, and 7. The distances are 3 and 3. The minimum magnetic force is 3, which is the maximum possible.

Example 2

Example 2

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

Output: 999999999

Explanation: The balls can be placed at positions 1 and 1000000000. The distance between them is 999999999, which is the maximum possible.

Example 3

Example 3

Input: position = [1,3,5,7,9], m = 3

Output: 4

Explanation: The balls can be placed at positions 1, 5, and 9. The distances are 4 and 4. The minimum magnetic force is 4, which is the maximum possible.

Constraints
  • 2 = position.length = 105
  • 1 = position[i] = 10?
  • All position[i] are distinct
  • 2 = m = position.length
Topics
Binary Search
Companies
Amazon Microsoft Apple Samsung Visa Walmart
Added 19 Jul 2026 60% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 7
3
3