Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Magnetic Force Between Two Balls

Medium Acceptance 60.00% Points 30.00

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.

Hints
Hint 1
N/A
Constraints
  • 2 = position.length = 105
  • 1 = position[i] = 10?
  • All position[i] are distinct
  • 2 = m = position.length
Companies
Amazon Microsoft Apple Samsung Visa + 1 more
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions