Skip to content

Commit 2c2cc0f

Browse files
authoredAug 17, 2020
Create magnetic-force-between-two-balls.cpp
1 parent b757e4c commit 2c2cc0f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
 
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(nlogn + nlogr), r is the range of positions
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maxDistance(vector<int>& position, int m) {
7+
sort(begin(position), end(position));
8+
int left = 0, right = position.back() - position.front();
9+
while (left <= right) {
10+
const auto& mid = left + (right - left) / 2;
11+
if (!check(position, m, mid)) {
12+
right = mid - 1;
13+
} else {
14+
left = mid + 1;
15+
}
16+
}
17+
return right;
18+
}
19+
20+
private:
21+
bool check(const vector<int>& position, int m, int x) {
22+
int count = 1, prev = position[0];
23+
for (int i = 1; i < position.size(); ++i) {
24+
if (position[i] - prev >= x) {
25+
++count;
26+
prev = position[i];
27+
}
28+
}
29+
return count >= m;
30+
}
31+
};

0 commit comments

Comments
 (0)
Please sign in to comment.