-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2517-maximum-tastiness-of-candy-basket.js
More file actions
47 lines (42 loc) · 1.1 KB
/
2517-maximum-tastiness-of-candy-basket.js
File metadata and controls
47 lines (42 loc) · 1.1 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 2517. Maximum Tastiness of Candy Basket
* https://leetcode.com/problems/maximum-tastiness-of-candy-basket/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[]} price
* @param {number} k
* @return {number}
*/
var maximumTastiness = function(price, k) {
price.sort((a, b) => a - b);
let left = 0;
let right = price[price.length - 1] - price[0];
let result = 0;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
let count = 1;
let prev = price[0];
for (let i = 1; i < price.length; i++) {
if (price[i] - prev >= mid) {
count++;
prev = price[i];
}
}
if (count >= k) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
};