#1449

Form Largest Integer With Digits That Add up to Target

Hard
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

Using dynamic programming, we can build a table that tracks the maximum number that can be formed for each possible cost up to the target. This allows us to efficiently find the largest number without generating all combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a DP array where dp[i] stores the maximum number string that can be formed with cost i.
  2. 2Step 2: Initialize dp[0] to an empty string since no cost means no digits.
  3. 3Step 3: For each digit from 1 to 9, update the DP array by checking if the current cost can be formed by adding this digit.
  4. 4Step 4: After filling the DP array, return dp[target] or '0' if it remains empty.
solution.py11 lines
1# Full working Python code
2
3def largestInteger(cost, target):
4    dp = [''] * (target + 1)
5    dp[0] = ''
6    for digit in range(1, 10):
7        for t in range(cost[digit - 1], target + 1):
8            if dp[t - cost[digit - 1]] != '':
9                new_number = dp[t - cost[digit - 1]] + str(digit)
10                dp[t] = max(dp[t], new_number)
11    return dp[target] if dp[target] else '0'

Complexity note: The complexity is O(n * m) where n is the target and m is the number of digits (which is constant at 9). This is efficient because we only iterate through the target cost and update the DP array.

  • 1Dynamic programming allows us to build solutions incrementally.
  • 2The order of digits matters for forming the largest number.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.