1552. Magnetic Force Between Two Balls #287
-
Topics: 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 Rick stated that magnetic force between two different balls at positions Given the integer array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the maximum possible minimum magnetic force between any two balls placed in baskets at given positions. The magnetic force between two balls at positions Approach
Let's implement this solution in PHP: 1552. Magnetic Force Between Two Balls <?php
/**
* @param Integer[] $position
* @param Integer $m
* @return Integer
*/
function maxDistance($position, $m) {
sort($position);
$n = count($position);
$low = 0;
$high = $position[$n - 1] - $position[0];
$ans = 0;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if (canPlaceBalls($position, $m, $mid)) {
$ans = $mid;
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return $ans;
}
/**
* @param $arr
* @param $m
* @param $d
* @return bool
*/
private function canPlaceBalls($arr, $m, $d) {
$count = 1;
$last = $arr[0];
$length = count($arr);
for ($i = 1; $i < $length; $i++) {
if ($arr[$i] - $last >= $d) {
$count++;
$last = $arr[$i];
if ($count >= $m) {
return true;
}
}
}
return $count >= $m;
}
// Example usage:
$position1 = array(1, 2, 3, 4, 7);
$m1 = 3;
echo maxDistance($position1, $m1) . "\n"; // Output: 3
$position2 = array(5, 4, 3, 2, 1, 1000000000);
$m2 = 2;
echo maxDistance($position2, $m2) . "\n"; // Output: 999999999
?> Explanation:
This approach efficiently narrows down the maximum possible minimum distance using binary search, ensuring an optimal solution with a time complexity of O(n log n) due to sorting and O(n log(max_distance)) due to the binary search and feasibility checks. |
Beta Was this translation helpful? Give feedback.
We need to determine the maximum possible minimum magnetic force between any two balls placed in baskets at given positions. The magnetic force between two balls at positions
x
andy
is defined as|x - y|
. The goal is to distributem
balls such that the minimum magnetic force between any two balls is maximized.Approach