The Closest Dessert Cost interview question involves a chef making a dessert with one base and multiple optional toppings. You are given the costs of various bases and toppings, and a target price. You must choose exactly one base and any number of toppings (at most two of each kind) to reach a total cost as close to the target as possible. If there's a tie, you should pick the lower cost.
This Backtracking interview pattern is popular at Google. It tests your ability to explore a search space with constraints. It’s a variation of the knapsack or subset-sum problem but with a specific "at most two of each" rule. Interviewers look for how you prune the search (e.g., if you're already way over the target, stop adding toppings) and how you handle the "lower cost on tie" requirement.
The problem is best solved using Backtracking or Recursion. You can think of it as a decision tree: for each topping, do you add zero, one, or two of it? Since the number of toppings is usually small, the search space is manageable. Alternatively, it can be modeled as Dynamic Programming, specifically a variation of the "Change Making" or "Bounded Knapsack" problem.
Target: 10
Bases: [5, 7]
Toppings: [2, 3]
5.5.2. Cost = 7.2. Cost = 9.3. Cost = 8.2 and one 3. Cost = 10 (Perfect match!).
...and so on.
The algorithm keeps track of the cost that minimizes abs(cost - target).When dealing with "closest value" problems with backtracking, always pass the current best cost as a reference or global variable to prune branches that have no hope of improving the current result.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Target Sum | Medium | Solve | |
| Inverse Coin Change | Medium | Solve | |
| Maximize Total Cost of Alternating Subarrays | Medium | Solve | |
| Minimum Increment Operations to Make Array Beautiful | Medium | Solve | |
| Zero Array Transformation IV | Medium | Solve |