Maximum number made up of distinct digits whose sum is equal to N
Given a positive integer N, the task is to find the largest positive number made up of distinct digits having the sum of its digits equal to N. If no such number exists, print “-1”.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 25
The number 98710 is the largest number that contains only unique digits and the sum of its digits (9 + 8 + 7 + 1 + 0) is N(= 25).
Input: N = 50
Approach: The given problem can be solved based on the following observations:
- If the value of N is at least 45: The required result is -1 as the largest number that can be made using non-repeating digits is 9876543210, whose sum of digits is 45.
- For all other values of N: To get the largest number, start from the largest digit i.e., 9, and keep decrementing it and adding it to the required number. The required number must contain a 0 at the end of it as it increases the value without changing the sum of digits.
Follow the steps below to solve the problem:
- If the given number N is greater than 45, then print “-1”.
- Otherwise, perform the following steps:
- Initialize a variable, say num as 0 to store the required result, and a variable, say digit, as 9.
- Iterate a loop until the values of N and digit are positive and perform the following steps:
- If the value of a digit is at most N, then multiply num by 10 and then add the value of digit to num and decrement the value of N by digit.
- Also, decrement the value of the digit by 1.
- Multiply the variable num by 10 and append digit 0 at the end.
- After completing the above steps, print the value of num as the resultant number.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)