Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1449. Form Largest Integer With Digits That Add up to Target

Explanation:

To solve this problem, we can use dynamic programming. We create a 1D array dp where dp[i] represents the maximum number we can form with a cost equal to i. We iterate over each digit cost and update the dp array accordingly. Finally, we build the result string by backtracking through the dp array.

  • Initialize dp array with size target + 1 and fill it with -1 (to indicate it's not possible to form a number with that cost).
  • Set dp[0] = 0 as the cost of forming number '0' is 0.
  • Iterate over each digit cost and update dp array.
  • Backtrack through the dp array to build the result string.

Time Complexity: O(target) where target is the given target value. Space Complexity: O(target) for the dp array.

:

class Solution {
    public String largestNumber(int[] cost, int target) {
        int[] dp = new int[target + 1];
        Arrays.fill(dp, -1);
        dp[0] = 0;
        
        for (int i = 1; i <= target; i++) {
            for (int j = 0; j < 9; j++) {
                if (i - cost[j] >= 0 && dp[i - cost[j]] >= 0) {
                    dp[i] = Math.max(dp[i], dp[i - cost[j]] + 1);
                }
            }
        }
        
        if (dp[target] < 0) {
            return "0";
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 8; i >= 0; i--) {
            while (target - cost[i] >= 0 && dp[target] == dp[target - cost[i]] + 1) {
                sb.append(i + 1);
                target -= cost[i];
            }
        }
        
        return sb.toString();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.