How to find the largest number with given digit sum s and number of digits d?
Input : s = 9, d = 2 Output : 90 Input : s = 20, d = 3 Output : 992
A Simple Solution is to consider all m digit numbers and keep track of maximum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).
There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from leftmost to rightmost (or from most significant digit to least significant).
We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from left to right, we put the highest digits on the left side, hence get the largest number. Below is implementation of the idea.
Largest number is 90
Time Complexity of this solution is O(m).
This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Find largest number smaller than N with same set of digits
- Find the Largest Cube formed by Deleting minimum Digits from a number
- Find smallest number with given number of digits and sum of digits
- Largest number not greater than N all the digits of which are odd
- Largest number with prime digits
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Largest palindromic number by permuting digits
- Largest number not greater than N which can become prime after rearranging its digits
- Largest number smaller than or equal to n and digits in non-decreasing order
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Maximize the given number by replacing a segment of digits with the alternate digits given
- Minimum number of digits to be removed so that no two consecutive digits are same
- Find the smallest number whose digits multiply to a given number n
- Find maximum number that can be formed using digits of a given number
Improved By : jit_t