1552. Magnetic Force Between Two Balls / Aggressive Cows
Problem Statement
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.
Constraints:
n == position.length
2 <= n <= 105
1 <= position[i] <= 109
All integers in
position
are distinct.2 <= m <= position.length
Intuition
Approach:
Place the cows various distaces and find the answer
Place at start and go ahead
Links
https://leetcode.com/problems/magnetic-force-between-two-balls/description/
Video Links
https://www.youtube.com/watch?v=R_Mfw4ew-Vo&ab_channel=takeUforward
Approach 1:
class Solution {
public:
bool canPlace(vector<int>& arr, int cows, int dist){
int ct_cows=1, last_cow=0;
for(int i=1; i<arr.size(); i++){
if(arr[i] - arr[last_cow] >= dist){
ct_cows++;
last_cow = i;
}
}
return ct_cows >= cows;
}
int maxDistance(vector<int>& arr, int cows) {
int n = arr.size();
sort(arr.begin(), arr.end());
int low = 1, high = arr[n-1] - arr[0], ans;
while(low<=high){
int dist = low+(high-low)/2;
if(canPlace(arr, cows, dist) == true){
ans = dist;
low = dist+1;
}
else
high = dist-1;
}
return ans;
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated