- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Find maximum number that can be formed using digits of a given number in C++
- Find the Largest number with given number of digits and sum of digits in C++
- Find the Largest Cube formed by Deleting minimum Digits from a number in Python
- Find the Largest Cube formed by Deleting minimum Digits from a number in C++
- Maximum possible time that can be formed from four digits in C++
- Finding the immediate bigger number formed with the same digits in JavaScript
- Program to find length of longest word that can be formed from given letters in python
- Count of alphabets whose ASCII values can be formed with the digits of N in C++
- Largest number with the given set of N digits that is divisible by 2, 3 and 5 in C++
- Largest number with prime digits in C++
- Find the count of numbers that can be formed using digits 3 and 4 only and having length at max N in C++
- Python - Find the latest valid time that can be obtained by replacing the unknown/hidden digits
- Program to find number of rectangles that can form the largest square in Python
- All possible strings of any length that can be formed from a given string?
- Find smallest number with given number of digits and sum of digits in C++

Advertisements