Rearrange Array to maximize number having Array elements as digits based on given conditions

Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible.

 Examples:

Input: arr[]={1, 3, 4, 2}, str=”0101” 
Output: 4 3 1 2 
Explanation: 
Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input: arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101” 
Output: 8 7 6 456 3 1 
Explanation: 
Array elements present at 0-chractered indices: {3, 7} 
Largest number that can be formed from the above two numbers is 73 
Array elements present at 1-chractered indices: {1, 456, 6, 8} 
Largest number that can be formed from the above two numbers is 864561 
Therefore, maximum number that can be generated from the array is 87645631 

 Approach: Follow the steps below to solve the problem: 



  1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
  2. Sort the arrays to form largest possible numbers from these two arrays.
  3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Comparison Function to sort()
int myCompare(int a, int b)
{
    string X = to_string(a);
    string Y = to_string(b);
 
    // Append Y at the end of X
    string XY = X.append(Y);
 
    // Append X at the end of Y
    string YX = Y.append(X);
 
    // Compare and return greater
    return XY.compare(YX) < 0 ? 1 : 0;
}
 
// Function to return the rearranged
// array in the form of largest
// possible number that can be formed
void findMaxArray(vector<int>& arr, string& str)
{
    int N = arr.size();
    vector<int> Z, O, ans(N);
 
    for (int i = 0; i < N; i++) {
        if (str[i] == '0') {
            Z.push_back(arr[i]);
        }
 
        else {
            O.push_back(arr[i]);
        }
    }
 
    // Sort them in decreasing order
    sort(Z.rbegin(), Z.rend(), myCompare);
    sort(O.rbegin(), O.rend(), myCompare);
 
    int j = 0, k = 0;
 
    // Generate the sorted array
    for (int i = 0; i < N; i++) {
        if (str[i] == '0') {
            ans[i] = Z[j++];
        }
        else {
            ans[i] = O[k++];
        }
    }
 
    for (int i = 0; i < N; i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 3, 456, 6, 7, 8 };
    string str = "101101";
    findMaxArray(arr, str);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
 
// Function to return the rearranged
// array in the form of largest
// possible number that can be formed
static void findMaxArray(int[] arr, String str)
{
    int N = arr.length;
    ArrayList<Integer> Z = new ArrayList<>(),
                       O = new ArrayList<>();
                        
    int[] ans = new int[N];
 
    for(int i = 0; i < N; i++)
    {
        if (str.charAt(i) == '0')
        {
            Z.add(arr[i]);
        }
        else
        {
            O.add(arr[i]);
        }
    }
 
    // Sort them in decreasing order
    Collections.sort(Z, new Comparator<Integer>()
    {
        public int compare(Integer a, Integer b)
        {
            String X = Integer.toString(a);
            String Y = Integer.toString(b);
             
            // Append Y at the end of X
            String XY = X + Y;
         
            // Append X at the end of Y
            String YX = Y + X;
         
            // Compare and return greater
            return XY.compareTo(YX) > 0 ? -1 : 1;
        }
    });
     
    Collections.sort(O, new Comparator<Integer>()
    {
        public int compare(Integer a, Integer b)
        {
            String X = Integer.toString(a);
            String Y = Integer.toString(b);
 
            // Append Y at the end of X
            String XY = X + Y;
         
            // Append X at the end of Y
            String YX = Y + X;
         
            // Compare and return greater
            return XY.compareTo(YX) > 0 ? -1 : 1;
        }
    });
     
    int j = 0, k = 0;
 
    // Generate the sorted array
    for(int i = 0; i < N; i++)
    {
        if (str.charAt(i) == '0')
        {
            ans[i] = Z.get(j++);
        }
        else
        {
            ans[i] = O.get(k++);
        }
    }
 
    for(int i = 0; i < N; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
 
// Driver code
public static void main (String[] args)
{
    int[] arr = { 1, 3, 456, 6, 7, 8 };
    String str = "101101";
     
    findMaxArray(arr, str);
}
}
 
// This code is contributed by offbeat

chevron_right


Output: 

8 7 6 456 3 1




 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : offbeat