#2517
Maximum Tastiness of Candy Basket
MediumArrayBinary SearchGreedySortingBinary SearchGreedy AlgorithmsSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages sorting and binary search. By sorting the prices, we can efficiently check if we can select k candies with a minimum tastiness using a greedy approach.
⚙️
Algorithm
3 steps- 1Step 1: Sort the price array.
- 2Step 2: Use binary search to determine the maximum possible tastiness.
- 3Step 3: For each mid value in the binary search, use a greedy approach to check if we can select k candies such that the minimum difference is at least mid.
solution.py21 lines
1def canSelectCandies(price, k, min_diff):
2 count = 1
3 last_selected = price[0]
4 for i in range(1, len(price)):
5 if price[i] - last_selected >= min_diff:
6 count += 1
7 last_selected = price[i]
8 if count == k:
9 return True
10 return False
11
12def maxTastiness(price, k):
13 price.sort()
14 left, right = 0, price[-1] - price[0]
15 while left < right:
16 mid = (left + right + 1) // 2
17 if canSelectCandies(price, k, mid):
18 left = mid
19 else:
20 right = mid - 1
21 return leftℹ
Complexity note: The sorting step takes O(n log n) time, and the binary search runs in O(log(max_diff)) where max_diff is the range of possible tastiness values. The greedy check runs in O(n), leading to an overall efficient solution.
- 1Sorting the prices allows for efficient selection of candies based on their price differences.
- 2Binary search helps in narrowing down the maximum tastiness efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.