Problem 1449

Abstract / Summary

Given a target sum, create the largest possible number by choosing digits that add up to that sum.

Note

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

Python 1449.py

class Solution:
    def largestNumber(self, cost: List[int], target: int) -> str:
        # highest digit per cost
        high = {}
        for i, c in enumerate(cost, 1):
            high[c] = i
        # ordered (by cost)
        digits = []
        for h in sorted(high):
            digits.append(( str(high[h]), h ))

        @cache
        def deeper(price):
            if price == 0:
                return "" # found a valid number

            best = ""
            for digit, dollars in digits:
                if dollars > price:
                    break

                # append more digits
                next = deeper(price - dollars)
                # failed, target not met
                if next == None:
                    continue

                have = digit + next
                # longer than before
                if len(have) >  len(best):
                    best = have
                # same length but higher digits
                if len(have) == len(best):
                    best = max(best, have)

            return best if best else None # None if target not met

        result = deeper(target)
        return result if result else "0"
39 lines | 1221 bytes | submitted April 8, 2024 | GitHub   29% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (40k+ submissions).

Typical patterns to solve this problem:
  • Array
  • 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 constructing the largest possible integer, represented as a string, whose total digit cost equals a given target. It receives an array cost where cost[i] is the price of digit i+1. The algorithm first builds a mapping from each distinct cost to the highest digit that can be bought for that cost, then explores all feasible combinations using a memoized depth-first search. The result is either the maximal string or "0" when no combination meets the target.

Key Steps

The first phase creates a dictionary that records, for every cost value, the greatest digit that can be purchased with that cost. This ensures that when multiple digits share the same price, the algorithm prefers the larger digit, which is essential for maximizing the final number.

high = {}
for i, c in enumerate(cost, 1):
    high[c] = i

Next, the dictionary is transformed into a list of (digit_string, cost) pairs sorted by cost. Sorting enables early termination of the inner loop when the remaining budget is insufficient for the current digit.

digits = []
for h in sorted(high):
    digits.append((str(high[h]), h))

The core of the solution is the recursive function deeper, decorated with @cache to memoize results for each sub-target price. The base case returns an empty string when the remaining price is exactly zero, indicating a valid combination has been found.

@cache
def deeper(price):
    if price == 0:
        return ""   # found a valid number

Inside the recursion, the function iterates over the pre-sorted digits. For each digit whose cost does not exceed the current price, it recursively attempts to build the remainder of the number. If the recursive call returns None, the branch is discarded because it cannot satisfy the exact target.

    best = ""
    for digit, dollars in digits:
        if dollars > price:
            break

        next = deeper(price - dollars)
        if next == None:
            continue

When a valid suffix next is obtained, the candidate string have is formed by concatenating the current digit with the suffix. The algorithm then selects the better candidate based on two criteria: longer length (more digits) and, for equal length, lexicographically larger value (higher digits in earlier positions). This comparison guarantees that the final string is the numerically largest possible.

        have = digit + next
        if len(have) > len(best):
            best = have
        if len(have) == len(best):
            best = max(best, have)

After exploring all options, the function returns the best candidate if any exists; otherwise it returns None to signal that the current price cannot be achieved.

    return best if best else None   # None if target not met

Finally, the top-level call invokes deeper with the original target. If a result is produced, it is returned; otherwise the function yields "0" to indicate impossibility.

result = deeper(target)
return result if result else "0"

Edge Cases

The implementation explicitly handles the situation where the target cannot be met by any combination of digits. In that scenario, every recursive path eventually returns None, causing the top-level result to be None and the function to output "0".

When the target is zero, the base case of deeper returns an empty string, which propagates upward. The final check treats an empty string as a valid result, leading to the return of "" from deeper and consequently "0" from the outer function, correctly representing that no digits can be formed without spending any cost.

If multiple digits share the same cost, the initial dictionary construction retains only the highest digit for each cost. This design choice ensures that the algorithm never chooses a lower digit when a higher one is equally affordable, thereby preserving maximality without needing additional tie-breaking logic later.

The sorted order of digits guarantees that once a digit’s cost exceeds the remaining budget, the loop terminates early. This prevents unnecessary recursive calls for digits that are guaranteed to be unaffordable, effectively handling cases where the cost list contains large values relative to the target.

Performance Optimizations

Memoization via @cache is the primary optimization. By caching the result of deeper for each distinct price, the algorithm avoids recomputing the same sub-problems multiple times. This dramatically reduces the exponential blow-up typical of naive recursive enumeration, especially when many different paths converge on the same remaining budget.

Sorting the digit-cost pairs by cost enables a cheap early-exit condition (if dollars > price: break). This prevents the inner loop from iterating over digits that are guaranteed to be too expensive for the current sub-target, cutting down the number of recursive invocations.

Storing only the highest digit for each cost in the high dictionary reduces the size of the search space. By discarding lower digits that would never be chosen in an optimal solution, the algorithm limits the number of branches explored at each recursion level.

The comparison logic that prefers longer strings first and then uses max for equal lengths ensures that the algorithm can stop exploring a branch as soon as it discovers a candidate that is already longer than any previously found solution. This implicit pruning avoids unnecessary deeper searches for shorter alternatives.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bucket of toy coins and a shop full of number stickers. Each sticker has a price written on it, and the goal is to spend exactly all your coins to make the biggest number possible.

First, the code looks at all the stickers to see which ones are the most valuable for the least amount of money. It decides which sticker gives the most bang for the buck and puts them in a special list sorted by price.

Next, it starts a game of exploration where it tries to build a giant number. It picks a sticker, subtracts its price from the total coins, and asks itself what the next best sticker would be. This happens over and over, like an endless puzzle where you keep adding pieces until you have no coins left.

As it builds these potential numbers, it remembers the ones that are the longest. Because a longer number is always bigger, the code keeps the longest one it finds. If two numbers are the same length, it checks which one starts with a bigger digit.

Finally, after testing all the ways to spend the coins, the code shows the giant number it built. If it discovers that no combination of stickers adds up to exactly the right amount of coins, it gives a zero to show that no number could be made.

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.22 | σ = 1.57

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++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
22 links | 12 authors | 7 languages

Videos

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

Solved On The Same Day

2 medium
3 solutions   April 8, 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