-
Notifications
You must be signed in to change notification settings - Fork 0
/
1552_MagneticField.cpp
55 lines (49 loc) · 1.86 KB
/
1552_MagneticField.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
1552. Magnetic Force Between Two Balls
Medium
Hint
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.
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.
*/
class Solution {
public:
int maxDistance(vector<int>& position, int m) {
sort(position.begin(), position.end());
int lo = 1;
int hi = (position.back() - position[0]) / (m - 1);
int ans = 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (canWePlace(position, mid, m)) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private:
bool canWePlace(const vector<int>& arr, int dist, int balls) {
int countBalls = 1;
int lastPlaced = arr[0];
for (int i = 1; i < arr.size(); i++) {
if (arr[i] - lastPlaced >= dist) {
countBalls++;
lastPlaced = arr[i];
}
if (countBalls >= balls) {
return true;
}
}
return false;
}
};