Maximum possible number with concatenations of K numbers from a given array


Finding the largest number that can be produced by concatenating K numbers from a given array is an exciting problem in the area of numerical manipulation and algorithmic difficulties. The sequence of concatenation must be carefully considered in this challenge because it affects the largest number's value.

The complexity of the "Maximum Possible Number with Concatenations of K Numbers from a Given Array" problem is explored in this article. We will investigate a step-by-step method, and look at the C++ algorithmic implementation. By the end of this article, readers will have a thorough understanding of how to approach this issue successfully.

Problem Statement

Given an array of numbers and an integer K, the task is to select K numbers from the array and concatenate them in a way that results in the maximum possible number. The concatenated value depends on the order in which the numbers are entered, therefore this is crucial. The objective is to create an algorithm that effectively resolves this issue.

Approach

  • Convert the numbers in the array to strings. This allows us to manipulate the numbers as characters and perform string operations.

  • Define a custom comparator function that compares two numbers by concatenating them in both orders: 'ab' and 'ba'. This comparison logic ensures that the numbers are sorted in a way that maximizes the concatenated value.

  • Use the custom comparator to sort the array of numbers in descending order. This places the numbers with the highest concatenated value at the beginning of the array.

  • Concatenate the first K numbers from the sorted array to obtain the maximum possible number.

  • Handle any leading zeros that may occur during the concatenation process. If all the numbers are zeros, the resulting maximum number should be '0'.

    • We can approach this condition after concatenating the K numbers by removing any leading zeros by finding the position of the first non−zero digit using 'find_first_not_of' and extracting the substring from that position to the end of the string.

    • If 'find_first_not_of' returns 'string::npos', indicating no non−zero digit was found, we set the maximum number to '0' explicitly as the entire array consists of zeros. This guarantees that the maximum number will be interpreted correctly.

Example

Now, let us implement the above approach in different programming languages: C++,and Java −

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool compareNums(const string& a, const string& b) {
   return (b + a) < (a + b);
}
string max_possible_num(vector<int>& num_vec, int k) {
   // Convert numbers to strings
   vector<string> num_to_str;
   for (int num : num_vec) {
      num_to_str.push_back(to_string(num));
   }
   // using the custom comparator, sort the vector
   sort(num_to_str.begin(), num_to_str.end(), compareNums);
   // start concatenating the first K numbers
   string maxNumber;
   for (int i = 0; i < k; ++i) {
      maxNumber += num_to_str[i];
   }
   // check and handle leading zeros
   size_t pos = maxNumber.find_first_not_of('0');
   if (pos != string::npos) {
      // extract the substring from the position where the non-zero digit is found to the end of the string.
      maxNumber = maxNumber.substr(pos);
   } else {
      maxNumber = "0";  // If all numbers are zeros
   }
   return maxNumber;
}
int main() {
   vector<int> num_vec = {17, 7, 2, 45, 72};
   int k = 4;
   string maxNumber = max_possible_num(num_vec, k);
   cout << "Maximum Number: " << maxNumber << endl;
   return 0;
}

Output

Maximum Number: 772452
import java.util.Arrays;
import java.util.Comparator;

public class MaxPossibleNumber {
   static class NumComparator implements Comparator<String> {
      @Override
      public int compare(String a, String b) {
         return (b + a).compareTo(a + b);
      }
   }
   static String maxPossibleNum(int[] numArray, int k) {
      // Convert numbers to strings
      String[] numToStr = Arrays.stream(numArray).mapToObj(String::valueOf)        .toArray(String[]::new);

      // Using the custom comparator, sort the array
      Arrays.sort(numToStr, new NumComparator());

      // Start concatenating the first K numbers
      StringBuilder maxNumber = new StringBuilder();
      for (int i = 0; i < k; ++i) {
         maxNumber.append(numToStr[i]);
      }

      // Check and handle leading zeros
      int pos = 0;
      while (pos < maxNumber.length() && maxNumber.charAt(pos) == '0') {
         pos++;
      }

      // Extract the substring from the position where the non-zero digit is found to the end of the string.
      maxNumber = new StringBuilder(maxNumber.substring(pos));

      return maxNumber.length() > 0 ? maxNumber.toString() : "0";
   }
   public static void main(String[] args) {
      int[] numArray = {17, 7, 2, 45, 72};
      int k = 4;
      String maxNumber = maxPossibleNum(numArray, k);
      System.out.println("Maximum Number: " + maxNumber);
   }
}

Output

Maximum Number: 772452

Complexity Analysis

Time Complexity

  • Converting numeric vector to string gve O(N), where N is the vector’s element count.

  • Sorting the array takes O(NlogN), where N is the input vector’s element count.

  • O(K), where K is the value given as the second input to the max_possible_num function, is the concatenation time for the first K numbers

  • As a result of the sorting step dominating the other processes, the code's overall time complexity is O(NlogN).

Space Complexity

  • The additional space needed for the num_to_str vector is O(N).

  • O(N), where N is the entire length of the concatenated numbers(because the maximum value K can possess is N), is the additional space required for the maxNumber string.

  • Therefore, the overall space complexity of the code is O(N).

Explanation Using Test Case

Example test case

Array: {17, 7, 2, 45, 72}
K: 4
  • Conversion to strings − The array is converted to strings: {"17", "7", "2", "45", "72"}.

  • Sorting the array − The custom comparator function compareNums, which compares numbers by concatenating them in both orders ('ab' and 'ba'), is used to sort the array. The array is changed to:{ "7", "72", "45", "2", "17" } after sorting (descending order).

  • Concatenating the first K numbers − The string "772452" is created by joining the first 4 integers in the sorted array.

  • Handling leading zeros − The code checks for leading zeros by using the 'find_first_not_of' function that searches for the first non-zero digit in the concatenated string. If a non−zero digit is found, the substring from that position to the end is extracted. But, In this case, there are no leading zeros in "772452", so the result stays the same.

  • Returning the maximum number − The maximum number, "772452", is returned from the max_possible_num function.

Output

Maximum Number: 772452.

Conclusion

An efficient strategy and algorithm are needed to find the greatest number that may be obtained by concatenating K numbers from a given array. We can quickly calculate the maximum number by converting a numeric array to a string, sorting the array with a unique comparator, and concatenating the appropriate elements. The applicability of the algorithm in solving the problem is demonstrated by the accompanying C++, and Java implementation.

Updated on: 23-Jan-2024

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements