Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Arrange given numbers to form the biggest number?
Here we will see how to generate the biggest number by rearranging the given numbers. Suppose there are {45, 74, 23} given, the program will find the largest number, that is 744523. Each digit will not be rearranged individually, but the whole numbers will be placed optimally to form the largest possible number.
To solve this problem, we use custom string comparison logic. The comparing function takes two numbers a and b, then concatenates them to form "ab" and "ba". Whichever concatenation gives the larger value determines the sorting order.
Syntax
int compare(const void *a, const void *b); void getLargest(char arr[][20], int n);
Algorithm
The algorithm works as follows −
- Compare Function: For two strings a and b, create "ab" and "ba", then compare which is lexicographically larger
- Sort: Use this custom comparison to sort the array in descending order
- Concatenate: Join all sorted numbers to form the final result
Example
Here's how to implement this solution in C using qsort with a custom comparator −
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
char *str1 = (char *)a;
char *str2 = (char *)b;
char ab[50], ba[50];
strcpy(ab, str1);
strcat(ab, str2);
strcpy(ba, str2);
strcat(ba, str1);
return strcmp(ba, ab);
}
void getLargest(char arr[][20], int n) {
qsort(arr, n, sizeof(arr[0]), compare);
printf("Largest number: ");
for (int i = 0; i < n; i++) {
printf("%s", arr[i]);
}
printf("<br>");
}
int main() {
char arr[][20] = {"45", "74", "23"};
int n = 3;
printf("Input numbers: ");
for (int i = 0; i < n; i++) {
printf("%s ", arr[i]);
}
printf("<br>");
getLargest(arr, n);
return 0;
}
Input numbers: 45 74 23 Largest number: 744523
How It Works
For the example {45, 74, 23}:
- Compare "45" and "74": "4574" vs "7445" ? "7445" is larger, so "74" comes first
- Compare "45" and "23": "4523" vs "2345" ? "4523" is larger, so "45" comes before "23"
- Final order: ["74", "45", "23"] ? Result: "744523"
Key Points
- The solution has O(n log n) time complexity due to sorting
- Custom comparison ensures optimal arrangement for maximum value
- Works for any set of positive integers converted to strings
Conclusion
This approach efficiently arranges numbers to form the largest possible concatenated value using custom string comparison. The key insight is comparing concatenated combinations rather than the numbers themselves.
