Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1774: Closest Dessert Cost

In this guide, we solve Leetcode #1774 Closest Dessert Cost in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Dynamic Programming, Backtracking

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10 Output: 10 Explanation: Consider the following combination (all 0-indexed): - Choose base 1: cost 7 - Take 1 of topping 0: cost 1 x 3 = 3 - Take 0 of topping 1: cost 0 x 4 = 0 Total: 7 + 3 + 0 = 10.

Python Solution

class Solution: def closestCost( self, baseCosts: List[int], toppingCosts: List[int], target: int ) -> int: def dfs(i, t): if i >= len(toppingCosts): arr.append(t) return dfs(i + 1, t) dfs(i + 1, t + toppingCosts[i]) arr = [] dfs(0, 0) arr.sort() d = ans = inf # 选择一种冰激淋基料 for x in baseCosts: # 枚举子集和 for y in arr: # 二分查找 i = bisect_left(arr, target - x - y) for j in (i, i - 1): if 0 <= j < len(arr): t = abs(x + y + arr[j] - target) if d > t or (d == t and ans > x + y + arr[j]): d = t ans = x + y + arr[j] return ans

Complexity

The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy