- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements
To Continue Learning Please Login
Login with Google