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.
classSolution { boolhelper(vector<int>& A, int k, longlong 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: intmaximumTastiness(vector<int>& A, int k){ sort(begin(A), end(A)); longlong l = 0, r = 1e9 + 1, res = 0; while(l <= r) { longlong 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; } };