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
Maximum Tastiness of Candy Basket INPUT price array (unsorted) 13 5 1 8 21 Sorted array 1 5 8 13 21 Input Values price = [13,5,1,8,21] k = 3 (select 3 candies) ALGORITHM STEPS 1 Sort Array [1, 5, 8, 13, 21] 2 Binary Search Setup lo=0, hi=20 (max diff) 3 Check Feasibility Can pick k items with min diff >= mid? 4 Update Search If yes: lo = mid + 1 If no: hi = mid - 1 Binary Search Progress mid=10: [1,13,21] OK mid=15: cannot pick 3 mid=8: [1,13,21] OK mid=9: cannot pick 3 Answer = 8 FINAL RESULT Optimal Selection (k=3) 1 13 21 Price Differences: |13-1| = 12 |21-13| = 8 Maximum Tastiness 8 min(12, 8) = 8 Output: 8 -- OK Key Insight: Use Binary Search on the answer (tastiness value). For each candidate tastiness 'mid', greedily check if we can select k candies from sorted array where consecutive picks differ by at least 'mid'. Time Complexity: O(n log n) for sorting + O(n log M) for binary search where M = max(price) - min(price). TutorialsPoint - Maximum Tastiness of Candy Basket | Binary Search on Answer Approach
Asked in
Google 25 Amazon 18 Meta 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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