...

/

Solution: Find the Largest Number Possible

Solution: Find the Largest Number Possible

Review the solution to the problem of finding the largest possible number in detail.

Solution: Greedy approach

using System;
class Program
{
/// <summary>
/// Finds the largest number with the given number of digits and sum of digits.
/// </summary>
/// <param name="numberOfDigits">Number of digits.</param>
/// <param name="sumOfDigits">Sum of digits.</param>
/// <returns>The possible largest number.</returns>
public static int[] FindLargestNumber(int numberOfDigits, int sumOfDigits)
{
// If the sum of digits is 0, then a number is possible only if the number of digits is 1.
if (sumOfDigits == 0)
{
if (numberOfDigits == 1)
{
return new int[] { 0 };
}
else
{
return new int[] { -1 };
}
}
// sumOfDigits is greater than the maximum possible sum.
if (sumOfDigits > 9 * numberOfDigits)
{
return new int[] { -1 };
}
int[] result = new int[numberOfDigits];
// Fill from most significant digit to least significant digit!
for (int i = 0; i < numberOfDigits; i++)
{
// Place 9 to make the number largest
if (sumOfDigits >= 9)
{
result[i] = 9;
sumOfDigits -= 9;
}
// If remaining sum becomes less than 9, then fill the remaining sum
else
{
result[i] = sumOfDigits;
sumOfDigits = 0;
}
}
return result;
}
// Driver code to test above function
public static void Main(string[] args)
{
int sumOfDigits1 = 20;
int numberOfDigits1 = 3;
Console.WriteLine("[" + string.Join(", ", FindLargestNumber(numberOfDigits1, sumOfDigits1)) + "]"); // Output: 9, 9, 2
int sumOfDigits2 = 100;
int numberOfDigits2 = 2;
Console.WriteLine("[" + string.Join(", ", FindLargestNumber(numberOfDigits2, sumOfDigits2)) + "]"); // Output: -1
}
}

Explanation

We can solve the problem using the greedy approach.

The idea is to fill all digits one by one, from the leftmost to the rightmost digit (or from the most significant digit to the least significant digit), then compare the remaining sum with 9. If the remaining sum ...