Problem Description
Given an array cost of length 9 where cost[i] represents the cost of painting the digit (i+1) and a target cost, find the largest possible integer (as a string) that can be painted such that the total cost equals target. The integer must only contain digits 1 to 9 and if no valid integer can be painted, return "0".
Key Insights
- To maximize the integer, we should use as many digits as possible because a longer number is numerically larger.
- Once the maximum number of digits is determined, prioritize placing larger digits in higher-value positions.
- Use dynamic programming to determine the maximum number of digits that can be painted for every possible cost up to target.
- The DP state dp[i] represents the maximum count of digits that can be formed with exactly cost i.
- After computing the maximum count, reconstruct the largest possible number by greedily picking the highest possible digit that maintains the optimal digit count at each step.
Space and Time Complexity
Time Complexity: O(target * 9) – We iterate through each target value and try all 9 digits. Space Complexity: O(target) – We maintain a DP array of size target + 1.
Solution
We solve the problem using dynamic programming. The main idea is:
- Initialize a DP array where dp[i] represents the maximum number of digits that can be formed with cost i. Set dp[0] = 0 and all other entries to a sentinel value (e.g., -infinity) to indicate an impossible cost.
- For each total cost from 1 to target, for each digit from 1 to 9 (using its corresponding cost), if the cost allows (i.e., current target i is at least the cost for that digit) and dp[i - digitCost] is valid, update dp[i] with the maximum of its current value and dp[i - digitCost] + 1.
- If dp[target] remains impossible, return "0".
- Otherwise, reconstruct the result by iteratively selecting, from the highest digit (9) down to 1, the digit that if chosen, ensures the remaining cost can still yield the required number of digits (i.e., dp[remainder] equals dp[remainder - digitCost] + 1). Append the chosen digit to the result string and decrement the remainder.
- Output the result string as the largest possible integer.