Form Largest Integer With Digits That Add up to Target Problem
Description
LeetCode Problem 1449.
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
- The cost of painting a digit
(i + 1)is given bycost[i](0-indexed). - The total cost used must be equal to
target. - The integer does not have
0digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".
Example 1:
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit cost
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
Example 2:
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
Example 3:
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It is impossible to paint any integer with total cost equal to target.
Constraints:
cost.length == 91 <= cost[i], target <= 5000
Solution
Approach: Max-Length DP, Then Greedy Digits
There are no 0 digits, so a number with more digits is always larger. The first goal is therefore the length: the most digits we can paint with a total cost of exactly target.
That is a complete knapsack. Let f[t] be the most digits with total cost exactly t, or -1 if t cannot be reached. f[0] = 0, and for each t:
f[t] = max(f[t - cost[d]] + 1) over the digits d with cost[d] <= t and f[t - cost[d]] >= 0.
If f[target] < 0 the answer is "0".
Among the numbers of maximum length, the largest one has the largest possible first digit, then the largest possible second digit, and so on. So we build it from left to right with the budget t = target: a digit d can go next when f[t - cost[d]] == f[t] - 1, which means the rest of the budget can still fill the remaining positions. Take the largest such digit, subtract its cost, and repeat.
The digits come out in non-increasing order (once a digit stops fitting it never fits again), so it is enough to try 9 down to 1 once, taking each digit as many times as it fits.
Complexity: O(9 · target) time and O(target) extra space.
class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
# f[t]: the most digits we can paint with a total cost of exactly t (-1 if impossible).
f = [0] + [-1] * target
for t in range(1, target + 1):
for c in cost:
if c <= t and f[t - c] >= 0:
f[t] = max(f[t], f[t - c] + 1)
if f[target] < 0:
return "0"
# More digits always means a larger number. Fill the positions from left to right with the
# largest digit that still lets the rest of the budget reach the maximum length.
ans = []
t = target
for d in range(9, 0, -1):
c = cost[d - 1]
while c <= t and f[t - c] == f[t] - 1:
ans.append(str(d))
t -= c
return "".join(ans)