Maximum Tastiness of Candy Basket - Problem
You are given an array of positive integers price where price[i] denotes the price of the i-th 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.
Input & Output
Example 1 — Basic Case
$
Input:
price = [13,5,1,8,21], k = 3
›
Output:
8
💡 Note:
Choose candies with prices [13, 5, 21]. The tastiness is min(|13-5|, |13-21|, |5-21|) = min(8, 8, 16) = 8.
Example 2 — Minimum Size
$
Input:
price = [4,2,5], k = 2
›
Output:
1
💡 Note:
Choose candies with prices [4, 5]. The tastiness is |4-5| = 1. This is optimal since choosing [2,4] or [2,5] gives tastiness 2 or 3.
Example 3 — All Candies
$
Input:
price = [1,3,1], k = 3
›
Output:
0
💡 Note:
We must choose all candies [1,3,1]. The tastiness is min(|1-3|, |1-1|, |3-1|) = min(2, 0, 2) = 0.
Constraints
- 2 ≤ price.length ≤ 105
- 1 ≤ price[i] ≤ 109
- 2 ≤ k ≤ price.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of candy prices and number k of candies to select
2
Process
Sort prices, then binary search on tastiness value
3
Output
Maximum tastiness (minimum difference) achievable
Key Takeaway
🎯 Key Insight: Sort the prices first, then binary search on the tastiness value while greedily selecting candies
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code