Maximum Tastiness of Candy Basket — LeetCode 2517 Python Solution

MediumGreedyArrayBinary SearchSorting
Problem
#2517
Reading time
4 min

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

Python
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 l

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview