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
๐Ÿญ Optimal Candy Selection StrategyStep 1: Sort Prices [1, 3, 7, 9] and Binary Search on Min DifferenceRange: [0, 8]Try mid = 4Greedy CheckUpdate RangeStep 2: Greedy Selection with min_diff = 41โœ“ Select3โœ— Skip7โœ“ Select9โœ— Not neededDifference: 7-1 = 6 โ‰ฅ 4 โœ“3-1 = 2 < 4Result: Can select k=2 candies with min_diff=4Selected basket: [1, 7] with tastiness = 6Continue binary search to find maximum possible min_diff...
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))!
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
48.0K Views
Medium-High Frequency
~25 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen