-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxDist.cpp
More file actions
35 lines (34 loc) · 937 Bytes
/
maxDist.cpp
File metadata and controls
35 lines (34 loc) · 937 Bytes
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
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;
}
};