Maximum Tastiness of Candy Basket - Problem
Imagine you're a candy connoisseur tasked with creating the most balanced candy basket possible! ๐ญ
You're given an array price where price[i] represents the price of the i-th candy. You need to select exactly k distinct candies to create a basket.
The tastiness of your basket is defined as the smallest absolute difference between the prices of any two candies in the basket. In other words, you want to avoid having candies that are too similar in price - the more spread out the prices, the more "tasteful" your selection!
Goal: Return the maximum possible tastiness you can achieve.
Example: If prices are [1, 3, 1] and k = 2, you could pick candies with prices [1, 3] giving tastiness = |3-1| = 2. This is optimal!
Input & Output
example_1.py โ Basic Case
$
Input:
price = [1,3,1], k = 2
โบ
Output:
2
๐ก Note:
We can select candies with prices [1,3]. The tastiness is min(|1-3|) = 2, which is the maximum possible.
example_2.py โ Multiple Options
$
Input:
price = [4,3,5,10], k = 2
โบ
Output:
5
๐ก Note:
We can select candies with prices [3,10] or [4,10] or [5,10]. The maximum tastiness is min(|3-10|, |4-10|, |5-10|) = min(7,6,5) = 5 from [5,10].
example_3.py โ Larger Basket
$
Input:
price = [1,2,5,8,13,21], k = 3
โบ
Output:
8
๐ก Note:
Optimal selection is [1,13,21] giving tastiness = min(|13-1|, |21-1|, |21-13|) = min(12,20,8) = 8.
Constraints
- 2 โค k โค price.length โค 105
- 1 โค price[i] โค 109
- Important: We need to select exactly k distinct candies
Visualization
Tap to expand
Understanding the Visualization
1
Sort the Prices
Arrange candy prices in ascending order: [1,3,7,9]
2
Binary Search Setup
Search for maximum minimum difference in range [0, max-min]
3
Greedy Selection
For each candidate difference, greedily select k candies with that spacing
4
Find Maximum
The largest feasible minimum difference is our answer
Key Takeaway
๐ฏ Key Insight: Instead of trying all combinations, we binary search on the answer (minimum difference) and greedily check feasibility - this reduces complexity from exponential to O(n log n log(range))!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code