2517. Maximum Tastiness of Candy Basket ( 類似2616
類似
T: O(nlogn)
S: O(1)
```java
class Solution {
public int maximumTastiness(int[] price, int k) {
Arrays.sort(price);
int left = 0;
int right = price[price.length-1] - price[0];
int result = 0;
while (left <= right) {
int mid = left + (right - left)/2;
int elementsUseNumber = 1;
int curNumber = price[0]; // choose candies
for (int i = 1; i < price.length;i++) {
if (price[i] - curNumber >= mid) { // if candidates can >= max_diff
elementsUseNumber++;
curNumber = price[i];
}
}
if (elementsUseNumber >= k) {
result = Math.max(result, mid);
left = mid + 1; // male k samller, so pick larger number
} else {
right = mid - 1;
}
}
return result;
}
}
/*
[13,5,1,8,21,2]
1 2 5 8 13 21
1 3.3 5 8
我叫這個 max_diff (8)
8 13 21
5. 8
13
want larger diff (choose pair)
5 13 21
8. 8
16
so how about to search the diff range (0 ~ price[last] - price[0]) and k?
max_diff = 8 k = 3
7
6 k = 4...
if we want to choose from more k cadidates, the max_diff will be lower
所以可以發現 max_diff 和 k 是有一個相對關係的....
所以可以用 binary search
T: O(nlogn)
S: O(1)
*/
```
Last updated