
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Biggest Number by Arranging Numbers in C++
In this problem, we are given an array of numbers and we have to find the largest value that can be made by changing them in a certain way. the condition for the arrangement is, the order of even numbers and odd numbers shall remain the same i.e. the order of all even numbers cannot be changed.
let's take an example to understand the concept better,
Input : {17, 80, 99, 27, 14 , 22} Output: 801799271422 Explanation: the order of Even and Odd numbers is : Even : 80 14 22 Odd : 17 99 27
Here 99 is the biggest number but 17 comes before it in the order of odd numbers so we have considered 80 first and then sequentially making the order of arrangement like − 80 17 99 27 14 22
Since we have understood the problem, let's try to generate a solution for this. Here we can’t go for or classical descending order as a constraints about the sequence of Even and Odd is defined. So we will have to maintain this sequence and check ok the biggest of the first elements of the Even and Odd orders. and then go like that. Let’s see an algorithm that would make this more clear.
Algorithm
Step 1 : Create two structures, one for even other for odd, this will maintain the sequence. Step 2 : Take one element from each structure and check which combination makes a large number. Example, if E is the even number and O is the odd number which are at the top of the structure. then we will check which one is Greater of EO and OE. Step 3 : Place the greater combination into the final sequence. Step 4 : Print the final sequence.
Example
Now, let's create a program based on this algorithm.
#include <bits/stdc++.h> using namespace std; string merge(vector<string> arr1, vector<string> arr2) { int n1 = arr1.size(); int n2 = arr2.size(); int i = 0, j = 0; string big = ""; while (i < n1 && j < n2) { if ((arr1[i]+arr2[j]).compare((arr2[j]+arr1[i])) > 0) big += arr1[i++]; else big += arr2[j++]; } while (i < n1) big += arr1[i++]; while (j < n2) big += arr2[j++] ; return big; } string largestNumber(vector<string> arr, int n) { vector<string> even, odd; for (int i=0; i<n; i++) { int lastDigit = arr[i].at(arr[i].size() - 1) - '0'; if (lastDigit % 2 == 0) even.push_back(arr[i]); else odd.push_back(arr[i]); } string biggest = merge(even, odd); return biggest; } int main() { vector<string> arr; arr.push_back("17"); arr.push_back("80"); arr.push_back("99"); arr.push_back("27"); arr.push_back("14"); arr.push_back("22"); int n = arr.size(); cout<<"Biggest possible number from the array is = "<<largestNumber(arr, n); return 0; }
Output
Biggest possible number from the array is = 801799271422