Maximum Tastiness of Candy Basket — LeetCode 2517 Python Solution
- Problem
- #2517
- Pattern
- Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k. The store sells baskets of k distinct candies.
Example
- Input
- price = [13,5,1,8,21,2], k = 3
- Output
- 8
- Explanation
- Choose the candies with the prices [13,5,21].
Python solution
class Solution:
def maximumTastiness(self, price: List[int], k: int) -> int:
def check(x: int) -> bool:
cnt, pre = 0, -x
for cur in price:
if cur - pre >= x:
pre = cur
cnt += 1
return cnt >= k
price.sort()
l, r = 0, price[-1] - price[0]
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return lComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2517. Maximum Tastiness of Candy Basket is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2517. Maximum Tastiness of Candy Basket?
- LeetCode 2517. Maximum Tastiness of Candy Basket is rated Medium on LeetCode.
- What topics does LeetCode 2517. Maximum Tastiness of Candy Basket cover?
- LeetCode 2517. Maximum Tastiness of Candy Basket is tagged Greedy, Array, Binary Search and Sorting on LeetCode.