Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions 1000+/1552. Magnetic Force Between Two Balls
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,36 @@ class Solution {
return count >= m;
}
}


class Solution {
public int maxDistance(int[] position, int m) {
Arrays.sort(position);
int low = 0;
int high = position[position.length-1];
while (low < high) {
int mid = low + (high-low+1)/2;
if (canPut(position, m, mid)) {
low = mid;
} else {
high = mid-1;
}
}
return low;
}

/*
* returns whether we can put m balls such that minimum distance between two consecutive ball is always greater than or equal to the max.
*/
private boolean canPut(int[] positions, int m, int max) {
int count = 1;
int last = positions[0];
for (int i = 0; i < positions.length; i++) {
if (positions[i] - last >= max) {
last = positions[i];
count++;
}
}
return count >= m;
}
}