Form Largest Integer With Digits That Add up to Target - Problem
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 0 digits.
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".
Input & Output
Example 1 — Basic Case
$
Input:
cost = [4,3,2,5,6,7,2,5,5], target = 7
›
Output:
"772"
💡 Note:
We can paint digit 7 twice (cost 2 each) and digit 2 once (cost 3), giving total cost 2+2+3=7. The digits 7,7,2 arranged in descending order give us 772.
Example 2 — No Solution
$
Input:
cost = [7,6,5,5,5,6,8,7,8], target = 5
›
Output:
"5"
💡 Note:
The minimum cost is 5 (for digits 3, 4, or 5). With target=5, we can afford exactly one digit. The largest digit that costs 5 is digit 5, so the result is "5".
Example 3 — Multiple Digits
$
Input:
cost = [2,4,6,2,4,6,4,4,4], target = 5
›
Output:
"0"
💡 Note:
Digits 1 and 4 cost 2 each. We could paint two of them for cost 4, leaving 1 remaining cost, but no digit costs 1. We could paint one digit costing 2, leaving 3 remaining, but no digit costs exactly 3. No combination of digits sums to exactly 5, so no solution exists.
Constraints
- cost.length == 9
- 1 ≤ cost[i] ≤ 5000
- 1 ≤ target ≤ 5000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code