Problem solution · Python

Closest Dessert Cost

Closest Dessert Cost: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
108 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Closest Dessert Cost, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 108 lines of Python from the credited upstream file closest-dessert-cost.py.
  • The implementation visibly relies on sequence storage, ordered lookup, cached states.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeClosest Dessert Cost · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * max(max_base, target + max_topping / 2)) ~= O(m * t)# Space: O(max(max_base, target + max_topping / 2)) ~= O(t) class Solution(object):    def closestCost(self, baseCosts, toppingCosts, target):        """        :type baseCosts: List[int]        :type toppingCosts: List[int]        :type target: int        :rtype: int        """        max_count = 2        max_base, max_topping = max(baseCosts), max(toppingCosts)        dp = [False]*(max(max_base, target+max_topping//2)+1)        for b in baseCosts:            dp[b] = True        for t in toppingCosts:            for _ in xrange(max_count):                for i in reversed(xrange(len(dp)-t)):                    if dp[i]:                        dp[i+t] = True        result = float("inf")        for i in xrange(1, len(dp)):            if not dp[i]:                continue            if abs(i-target) < abs(result-target):                result = i            if i >= target:                break        return result             # Time:  O(n * 3^m)# Space: O(m * t)class Solution2(object):    def closestCost(self, baseCosts, toppingCosts, target):        """        :type baseCosts: List[int]        :type toppingCosts: List[int]        :type target: int        :rtype: int        """        max_count = 2        def backtracking(toppingCosts, i, cost, target, lookup, result):            if (i, cost) in lookup:                return            lookup.add((i, cost))            if cost >= target or i == len(toppingCosts):                if (abs(cost-target), cost) < (abs(result[0]-target), result[0]):                    result[0] = cost                return            for j in xrange(max_count+1):                backtracking(toppingCosts, i+1, cost+j*toppingCosts[i], target, lookup, result)         result = [float("inf")]        lookup = set()        for b in baseCosts:            backtracking(toppingCosts, 0, b, target, lookup, result)        return result[0]  # Time:  O(3^m*log(3^m)) + O(n*log(3^m)) = O(m*(3^m + n))# Space: O(3^m)import bisect  class Solution3(object):    def closestCost(self, baseCosts, toppingCosts, target):        """        :type baseCosts: List[int]        :type toppingCosts: List[int]        :type target: int        :rtype: int        """        max_count = 2        combs = set([0])        for t in toppingCosts:            combs = set([c+i*t for c in combs for i in xrange(max_count+1)])        result, combs = float("inf"), sorted(combs)        for b in baseCosts:            idx = bisect.bisect_left(combs, target-b)            if idx < len(combs):                result = min(result, b+combs[idx], key=lambda x: (abs(x-target), x))            if idx > 0:                result = min(result, b+combs[idx-1], key=lambda x: (abs(x-target), x))                return result  # Time:  O(n * 3^m)# Space: O(3^m)class Solution4(object):    def closestCost(self, baseCosts, toppingCosts, target):        """        :type baseCosts: List[int]        :type toppingCosts: List[int]        :type target: int        :rtype: int        """        max_count = 2        combs = set([0])        for t in toppingCosts:            combs = set([c+i*t for c in combs for i in xrange(max_count+1)])        result = float("inf")        for b in baseCosts:            for c in combs:                result = min(result, b+c, key=lambda x: (abs(x-target), x))              return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗