Problem 1774

Abstract / Summary

Given costs of different ingredients and a target price, find the closest possible cost by choosing at least two ingredients.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1774.py

class Solution:
    def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
        # return difference but prefer cheaper price
        best = lambda paid : abs(target - paid - 0.1)

        @cache
        def deeper(paid, pos):
            # reach target or out of toppings
            if paid >= target or pos == len(toppingCosts):
                return paid

            # 0, 1 or 2 of each topping
            top = [ deeper(paid + i * toppingCosts[pos], pos + 1) for i in ( 0, 1, 2 ) ]
            return sorted(top, key = best)[0]

        desserts = [ deeper(b, 0) for b in baseCosts ]
        return sorted(desserts, key = best)[0]
17 lines | 693 bytes | submitted May 23, 2024 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of finding a dessert price that is closest to a given target value. It combines a set of mandatory base costs with optional toppings, each of which may be used zero, one, or two times. The algorithm explores all feasible price combinations and selects the one whose distance to the target is minimal, preferring the cheaper option when distances are equal.

Core Logic

The entry point is the closestCost method, which receives three arguments: a list of base costs, a list of topping costs, and the target price. Inside the method a small helper lambda named best is defined. This lambda computes a modified distance metric: it subtracts a tiny constant (0.1) from the absolute difference between the target and a candidate price. By doing so, when two prices have the same absolute difference, the smaller price yields a slightly lower metric and is therefore chosen.

best = lambda paid: abs(target - paid - 0.1)

Recursive Exploration

The heart of the solution is the nested deeper function, which is memoized with @cache. The function takes the current accumulated price (paid) and the index of the topping being considered (pos). It terminates early in two situations: when the accumulated price has already reached or exceeded the target, or when all topping types have been processed. In either case the current price is returned as a candidate.

@cache
def deeper(paid, pos):
    if paid >= target or pos == len(toppingCosts):
        return paid

If the recursion continues, the function evaluates three possibilities for the current topping: using none, using one, or using two units. For each choice it recursively calls itself with the updated price and advances to the next topping index. The three resulting candidate prices are collected in a list named top.

top = [deeper(paid + i * toppingCosts[pos], pos + 1) for i in (0, 1, 2)]

The list top is then sorted using the best metric, and the first element-i.e., the price that is closest to the target according to the defined preference-is returned.

return sorted(top, key=best)[0]

Base Cost Aggregation

After defining the recursive helper, the algorithm iterates over each base cost. For each base price it invokes deeper starting at position 0, thereby exploring all topping combinations that can be added to that particular base. The resulting candidate prices are stored in the list desserts.

desserts = [deeper(b, 0) for b in baseCosts]

Finally, the list desserts is sorted with the same best metric, and the first element-representing the overall optimal dessert price-is returned as the answer.

return sorted(desserts, key=best)[0]

Edge Cases Handled

The recursion includes a guard that stops further exploration once the accumulated price meets or exceeds the target. This ensures that prices that would overshoot the target are still considered, but deeper branching that would only increase the price further is avoided. Consequently, the algorithm correctly handles scenarios where the exact target cannot be reached, returning the nearest lower or higher price as appropriate.

When the list of topping costs is empty, the base case pos == len(toppingCosts) is triggered immediately, and the function simply returns each base price. This covers the edge case of having no optional toppings.

If a base price alone already exceeds the target, the early termination condition paid >= target causes the recursion to return that base price without attempting to add any toppings, thereby respecting the constraint that adding more toppings would only increase the overshoot.

Performance Optimizations

Memoization via @cache dramatically reduces redundant work. Since the same (paid, pos) pair can be reached through different topping selection paths, caching ensures that each unique state is computed only once. This eliminates exponential recomputation that would otherwise arise from the three-way branching at each topping level.

The early-exit condition paid >= target prunes the search space. Once the accumulated price reaches the target, any further addition of toppings would only increase the distance, so the recursion stops, preventing unnecessary deeper calls.

Sorting with the custom best key is performed on very small lists (three elements for each topping step and the number of base costs for the final selection). The overhead is negligible, yet it provides a concise way to enforce the “cheaper when tied” rule without extra conditional logic.

Overall, the combination of memoization, early termination, and targeted sorting yields an efficient exploration of the feasible price space while adhering to the problem’s preference criteria.

written by openai gpt

ELI5 - Simplified Explanation

Imagine building a giant ice cream treat made of many delicious layers. The goal is to reach a very specific size that is just right.

There are two kinds of ingredients to choose from. First, there are the base parts that start the treat. Then, there are the toppings that can be stacked up. For every single topping, there is a choice to add nothing at all, add one scoop, or even add two scoops. This creates a branching path of possibilities, almost like following different trails in a maze.

The code works by exploring these branches one by one. It looks at every base and then tries every combination of toppings. At each step, it checks how close the current treat is to the target size. Because some combinations might reach the exact same size, the logic remembers what it has seen before to save time.

Once all the combinations are checked, the code gathers all the final sizes it found. It then sorts them to find the one that sits closest to the target. If two sizes are equally close, it picks the smaller one to make sure everything fits the goal perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.41 | σ = 1.28

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python JS Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
wisdompeak C++
24 links | 14 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 solutions   May 23, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality