Closest Dessert Cost - Problem

You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:

  • There must be exactly one ice cream base.
  • You can add one or more types of topping or have no toppings at all.
  • There are at most two of each type of topping.

You are given three inputs:

  • baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
  • toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
  • target, an integer representing your target price for dessert.

You want to make a dessert with a total cost as close to target as possible.

Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.

Input & Output

Example 1 — Basic Case
$ Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
Output: 10
💡 Note: Consider base cost 7 with 1 topping of cost 3: 7 + 3 = 10, which exactly equals target 10
Example 2 — Multiple Closest
$ Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
Output: 17
💡 Note: Base 3 + 2×4 + 2×5 = 3 + 8 + 10 = 21 (distance 3), Base 2 + 2×4 + 1×5 = 2 + 8 + 5 = 15 (distance 3), and Base 3 + 2×4 + 1×5 = 17 (distance 1). The closest is 17.
Example 3 — Lower Cost Tie
$ Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9
Output: 8
💡 Note: Base 3 + 1×5 = 8 (distance 1), Base 10 + 0 toppings = 10 (distance 1). Both have same distance but 8 < 10, so return 8

Constraints

  • n == baseCosts.length
  • m == toppingCosts.length
  • 1 ≤ n, m ≤ 10
  • 1 ≤ baseCosts[i], toppingCosts[i] ≤ 104
  • 1 ≤ target ≤ 104

Visualization

Tap to expand
Closest Dessert Cost: Find combination closest to targetBase Costs17Topping Costs34Target10Each topping: 0, 1, or 2 timesPossible combinations:Base 1: 1, 4, 5, 7, 8, 9, 11Base 7: 7, 10, 11, 13, 14, 15, 17Result: 10Distance 0 from target - perfect match!
Understanding the Visualization
1
Input
Base costs [1,7], topping costs [3,4], target 10
2
Process
Try each base with all possible topping combinations (0-2 of each)
3
Output
Return cost closest to target (prefer lower if tie)
Key Takeaway
🎯 Key Insight: Use backtracking to explore all base + topping combinations, track closest to target
Asked in
Amazon 15 Google 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen