Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2517: Maximum Tastiness of Candy Basket

In this guide, we solve Leetcode #2517 Maximum Tastiness of Candy Basket in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Greedy, Array, Binary Search, Sorting

Intuition

The problem structure suggests a monotonic decision, which makes binary search a natural fit.

By halving the search space each step, we reach the answer efficiently.

Approach

Search either directly on a sorted array or on the answer space using a check function.

Each check is fast, and the logarithmic search keeps the overall runtime low.

Steps:

  • Define the search bounds.
  • Check the mid point condition.
  • Narrow the bounds until convergence.

Example

Input: price = [13,5,1,8,21,2], k = 3 Output: 8 Explanation: Choose the candies with the prices [13,5,21]. The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8. It can be proven that 8 is the maximum tastiness that can be achieved.

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 l

Complexity

The time complexity is O(log n) or O(n log n). The space complexity is O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy