[LeetCode] Maximum Tastiness of Candy Basket

2517. Maximum Tastiness of Candy Basket

You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k.

The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.

Return the maximum tastiness of a candy basket.

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
class Solution {
bool helper(vector<int>& A, int k, long long m) {
int res = 1, last = A[0];
for(int i = 1; i < A.size() and res < k; i++) {
if(last + m <= A[i]) {
last = A[i];
res += 1;
}
}
return res >= k;
}
public:
int maximumTastiness(vector<int>& A, int k) {
sort(begin(A), end(A));
long long l = 0, r = 1e9 + 1, res = 0;
while(l <= r) {
long long m = l + (r - l) / 2;
bool pass = helper(A,k,m);
if(pass) {
res = max(res,m);
l = m + 1;
} else r = m - 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/25/PS/LeetCode/maximum-tastiness-of-candy-basket/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.