#1774

Closest Dessert Cost

Medium
ArrayDynamic ProgrammingBacktrackingDynamic ProgrammingCombinatorial Optimization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

We can use a dynamic programming approach to efficiently calculate all possible costs with toppings. By iterating through the toppings and updating possible costs, we can find the closest cost to the target without generating all combinations explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a set of possible costs with just the base costs.
  2. 2Step 2: For each topping, update the possible costs by considering adding 0, 1, or 2 of that topping to each existing cost.
  3. 3Step 3: After processing all toppings, find the closest cost to the target from the set of possible costs.
solution.py11 lines
1# Full working Python code
2
3def closestCost(baseCosts, toppingCosts, target):
4    possibleCosts = set(baseCosts)
5    for topping in toppingCosts:
6        newCosts = set()
7        for cost in possibleCosts:
8            newCosts.add(cost + topping)
9            newCosts.add(cost + 2 * topping)
10        possibleCosts.update(newCosts)
11    return min(possibleCosts, key=lambda x: (abs(x - target), x))

Complexity note: The time complexity is O(n * m) where n is the number of base costs and m is the number of toppings. This is because we iterate through each topping for each base cost.

  • 1Understanding how to combine items with constraints is crucial.
  • 2Dynamic programming can often simplify problems that seem combinatorial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.