Skip to content

Commit 80c2fde

Browse files
committed
feat(leetcode): add No.1552
1 parent 7d2553c commit 80c2fde

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// https://leetcode.com/problems/minimum-operations-to-make-array-equal/
2+
// algorithms
3+
// Medium (45.46%)
4+
// Total Accepted: 7,092
5+
// Total Submissions: 15,602
6+
7+
8+
class Solution {
9+
public int maxDistance(int[] position, int m) {
10+
Arrays.sort(position);
11+
int len = position.length;
12+
if (m == 2) {
13+
return position[len - 1] - position[0];
14+
}
15+
16+
int sum = position[len - 1] - position[0];
17+
int avg = sum / (m - 1);
18+
int l = 1, r = avg, mid = -1;
19+
int res = 1;
20+
21+
while (l <= r) {
22+
mid = l + (r - l) / 2;
23+
if (check(position, m - 1, mid)) {
24+
res = mid;
25+
l = mid + 1;
26+
} else {
27+
r = mid - 1;
28+
}
29+
}
30+
31+
return res;
32+
}
33+
34+
private boolean check(int[] position, int m, int dis) {
35+
int len = position.length;
36+
int beginIdx = 0;
37+
for (int i = 1; i < len; i++) {
38+
if (position[i] - position[beginIdx] >= dis) {
39+
m--;
40+
beginIdx = i;
41+
}
42+
43+
if (m == 0) {
44+
return true;
45+
}
46+
}
47+
48+
return false;
49+
}
50+
51+
}

0 commit comments

Comments
 (0)