LC.P2517[礼盒的最大甜蜜度]

方法一:贪心+二分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int maximumTastiness(int[] price, int k) {
Arrays.sort(price);
int l = 0, r = price[price.length - 1] - price[0];
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(price, k, mid)) l = mid;
else r = mid - 1;

}
return l;
}

private boolean check(int[] price, int k, int x) {
int cnt = 0, pre = -x;
for (int cur : price) {
if (cur - pre >= x) {
pre = cur;
++cnt;
}
}
return cnt >= k;
}
}