Problem Description
Given a list of ice cream base costs and topping costs, where you must choose exactly one base and may add 0 or more toppings (with up to two of each topping allowed), determine the total dessert cost that is closest to a target value. If there are ties, choose the lower cost.
Key Insights
- The base cost must be chosen exactly once; toppings are optional and each topping can be used 0, 1, or 2 times.
- There are at most 3^m topping combinations (m ≤ 10), which is feasible with a backtracking/DFS approach.
- Use DFS (or recursion) to generate all valid topping additions for each base and update an answer based on how close it is to the target.
- If the current cost exceeds the target in a DFS branch, further additions will only increase the difference, so that branch can be pruned.
Space and Time Complexity
Time Complexity: O(n * 3^m), where n is the number of bases and m is the number of toppings. Space Complexity: O(m), which is the recursion depth in the DFS.
Solution
We iterate over each base cost and use a recursive DFS to explore the three possibilities (0, 1, or 2 of each topping) for every topping in toppingCosts. A global (or an outer scoped) variable tracks the best dessert cost found so far. In the DFS, we update this best cost by comparing the absolute differences between the current cost and the target. To optimize, if the current cost exceeds the target, further topping additions will only worsen the difference, so the recursion can stop early. This approach covers all valid combinations and ensures we choose the closest cost (or the lower one in the event of a tie).