Suppose we have a list of numbers called nums, we have to rearrange its order to form the largest possible number and return that as a string.
So, if the input is like nums = [20, 8, 85, 316], then the output will be "88531620".
To solve this, we will follow these steps −
- Define an array temp
- for each item i in nums:
- insert i into temp as string
- sort the array temp based on lexicographic sequence (check for two strings a, b when a concatenate b is larger than b concatenate a or not)
- for each string s in temp:
- res := res concatenate s
- return res
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
static bool cmp(string a, string b) {
return (a + b) >= (b + a);
}
string solve(vector<int>& nums) {
vector<string> temp;
for (int i : nums) {
temp.push_back(to_string(i));
}
sort(temp.begin(), temp.end(), cmp);
string res;
for (string s : temp) {
res += s;
}
return res;
}
int main(){
vector<int> v = {20, 8, 85, 316};
cout << solve(v);
}Input
{20, 8, 85, 316}Output
88531620