Find the largest number that can be formed with the given digits in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of digits. We have to find the maximum number that can be obtained using all digits of the array. So if the array is like [3, 3, 9, 6, 2, 5], then maximum number can be 965332.

From the problem, we can see that we can easily sort the digits in non-increasing order, then print them. But we can solve this using more efficient way. We can create one array of size 10 to store the frequency of each digit, then print the numbers from 9 to 0 accordingly.

Example

 Live Demo

#include <iostream>
#include <string>
using namespace std;
int maxNumFromNum(int arr[], int n) {
   int freq[10] = {0};
   for (int i=0; i<n; i++)
   freq[arr[i]]++;
   int res = 0, mul = 1;
   for (int i = 0; i <= 9; i++) {
      while (freq[i] > 0) {
         res = res + (i * mul);
         freq[i]--;
         mul = mul * 10;
      }
   }
   return res;
}
int main() {
   int digits[] = {3, 3, 9, 6, 2, 5};
   int n = sizeof(digits)/sizeof(digits[0]);
   cout << "Maximum number: " << maxNumFromNum(digits, n);
}

Output

Maximum number: 965332
raja
Published on 18-Dec-2019 16:07:00
Advertisements