Open In App

Maximum array from two given arrays keeping order same

Last Updated : 28 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two same-sized arrays A[] and B[] (both arrays contain distinct elements individually but may have some common elements), the task is to form a third (or result) array of the same size. The resulting array should have maximum n elements from both arrays. It should have chosen elements of A[] first, then chosen elements of B[] in the same order as they appear in original arrays. If there are common elements, then only one element should be present in res[] and priority should be given to A[].

Examples:  

Input :  A[] =  [ 9 7 2 3 6 ]
         B[] =  [ 7 4 8 0 1 ]
Output : res[] = [9 7 6 4 8]
res[] has maximum n elements of both A[] 
and B[] such that elements of A[] appear
first (in same order), then elements of B[].
Also 7 is common and priority is given to
A's 7.

Input :  A[] = [ 6 7 5 3 ]
         B[] = [ 5 6 2 9 ] 
Output : res[] = [ 6 7 5 9 ]
  1. Create copies of both arrays and sort the copies in decreasing order. 
  2. Use a hash to pick unique n maximum elements of both arrays, giving priority to A[]. 
  3. Initialize result array as empty. 
  4. Traverse through A[], copy those elements of A[] that are present in the hash. This is done to keep the order of elements the same. 
  5. Repeat step 4 for B[]. This time we only consider those elements that are not present in A[] (Do not appear twice in the hash).

Below is the implementation of the above idea. 

C++




// Make a set of maximum elements from two
// arrays A[] and B[]
#include <bits/stdc++.h>
using namespace std;
 
void maximizeTheFirstArray(int A[], int B[], int n)
{
    // Create copies of A[] and B[] and sort
    // the copies in descending order.
    vector<int> temp1(A, A + n);
    vector<int> temp2(B, B + n);
    sort(temp1.begin(), temp1.end(), greater<int>());
    sort(temp2.begin(), temp2.end(), greater<int>());
 
    // Put maximum n distinct elements of
    // both sorted arrays in a map.
    unordered_map<int, int> m;
    int i = 0, j = 0;
    while (m.size() < n) {
        if (temp1[i] >= temp2[j]) {
            m[temp1[i]]++;
            i++;
        }
        else {
            m[temp2[j]]++;
            j++;
        }
    }
 
    // Copy elements of A[] to that
    // are present in hash m.
    vector<int> res;
    for (int i = 0; i < n; i++)
        if (m.find(A[i]) != m.end())
            res.push_back(A[i]);
 
    // Copy elements of B[] to that
    // are present in hash m. This time
    // we also check if the element did
    // not appear twice.
    for (int i = 0; i < n; i++)
        if (m.find(B[i]) != m.end() && m[B[i]] == 1)
            res.push_back(B[i]);
 
    // print result
    for (int i = 0; i < n; i++)
        cout << res[i] << " ";
}
 
// driver program
int main()
{
    int A[] = { 9, 7, 2, 3, 6 };
    int B[] = { 7, 4, 8, 0, 1 };
    int n = sizeof(A) / sizeof(A[0]);
    maximizeTheFirstArray(A, B, n);
    return 0;
}


Java




// Make a set of maximum elements from two
// arrays A[] and B[]
import java.io.*;
import java.util.*;
class GFG
{
     
    static void maximizeTheFirstArray(int[] A, int[] B,int n)
    {
       
        // Create copies of A[] and B[] and sort
        // the copies in descending order.
        ArrayList<Integer> temp1 = new ArrayList<Integer>();
        ArrayList<Integer> temp2 = new ArrayList<Integer>();
        for(int i : A)
        {
            temp1.add(i);
        }
        for(int i:B)
        {
            temp2.add(i);
        }
        Collections.sort(temp1, Collections.reverseOrder());
        Collections.sort(temp2, Collections.reverseOrder());
         
        // Put maximum n distinct elements of
        // both sorted arrays in a map.
        Map<Integer,Integer> m = new HashMap<>();
        int i = 0, j = 0;
        while (m.size() < n)
        {
             if (temp1.get(i) >= temp2.get(j))
             {
                if(m.containsKey(temp1.get(i)))
                {
                    m.put(temp1.get(i), m.get(temp1.get(i)) + 1);
                }
                else
                {
                    m.put(temp1.get(i), 1);
                }
                i++;
             }
             else
             {
                if(m.containsKey(temp2.get(j)))
                {
                    m.put(temp2.get(j), m.get(temp2.get(j)) + 1);
                }
                else
                {
                    m.put(temp2.get(j), 1);
                }
                j++;
             }
        }
         
        // Copy elements of A[] to that
        // are present in hash m.
        ArrayList<Integer> res = new ArrayList<Integer>();
        for (i = 0; i < n; i++)
            if (m.containsKey(A[i]))
               res.add(A[i]);
      
        // Copy elements of B[] to that
        // are present in hash m. This time
        // we also check if the element did
        // not appear twice.
        for (i = 0; i < n; i++)
            if (m.containsKey(B[i]) && m.get(B[i]) == 1)
               res.add(B[i]);
      
        // print result
        for (i = 0; i < n; i++)
            System.out.print(res.get(i)+" ");
    }
      
    // Driver program   
    public static void main (String[] args)
    {
        int A[] = { 9, 7, 2, 3, 6 };
        int B[] = { 7, 4, 8, 0, 1 };
        int n = A.length;
        maximizeTheFirstArray(A, B, n);
    }
}
 
// This code is contributed by rag2127


Python3




# Python3 program to implement the
# above approach
# Make a set of maximum elements
# from two arrays A[] and B[]
from collections import defaultdict
 
 
def maximizeTheFirstArray(A, B, n):
 
    # Create copies of A[] and B[]
    # and sort the copies in
    # descending order.
    temp1 = A.copy()
    temp2 = B.copy()
    temp1.sort(reverse=True)
    temp2.sort(reverse=True)
 
    # Put maximum n distinct
    # elements of both sorted
    # arrays in a map.
    m = defaultdict(int)
    i = 0
    j = 0
 
    while (len(m) < n):
        if (temp1[i] >= temp2[j]):
            m[temp1[i]] += 1
            i += 1
        else:
            m[temp2[j]] += 1
            j += 1
 
    # Copy elements of A[] to that
    # are present in hash m.
    res = []
 
    for i in range(n):
        if (A[i] in m):
            res.append(A[i])
 
    # Copy elements of B[] to that
    # are present in hash m. This time
    # we also check if the element did
    # not appear twice.
    for i in range(n):
        if (B[i] in m and
                m[B[i]] == 1):
            res.append(B[i])
 
    # Print result
    for i in range(n):
        print(res[i], end=" ")
 
 
# Driver code
if __name__ == "__main__":
 
    A = [9, 7, 2, 3, 6]
    B = [7, 4, 8, 0, 1]
    n = len(A)
    maximizeTheFirstArray(A, B, n)
 
# This code is contributed by Chitranayal


C#




// Make a set of maximum elements from two
// arrays A[] and B[]
using System;
using System.Collections.Generic;
 
class GFG{
 
static void maximizeTheFirstArray(int[] A, int[] B,
                                  int n)
{
     
    // Create copies of A[] and B[] and sort
    // the copies in descending order.
    List<int> temp1 = new List<int>();
    List<int> temp2 = new List<int>();
     
    foreach(int i in A)
    {
        temp1.Add(i);
    }
     
    foreach(int i in B)
    {
        temp2.Add(i);
    }
     
    temp1.Sort();
    temp1.Reverse();
    temp2.Sort();
    temp2.Reverse();
      
    // Put maximum n distinct elements of
    // both sorted arrays in a map.
    Dictionary<int,
               int> m = new Dictionary<int,
                                       int>();
    int I = 0, j = 0;
    while (m.Count < n)
    {
        if (temp1[I] >= temp2[j])
        {
            if (m.ContainsKey(temp1[I]))
            {
                m[temp1[I]]++;
            }
            else
            {
                m.Add(temp1[I], 1);
            }
            I++;
        }
        else
        {
            if (m.ContainsKey(temp2[j]))
            {
                m[temp2[j]]++;
            }
            else
            {
                m.Add(temp2[j], 1);
            }
            j++;
        }
    }
 
    // Copy elements of A[] to that
    // are present in hash m.
    List<int> res = new List<int>();
    for(int i = 0; i < n; i++)
        if (m.ContainsKey(A[i]))
            res.Add(A[i]);
   
    // Copy elements of B[] to that
    // are present in hash m. This time
    // we also check if the element did
    // not appear twice.
    for(int i = 0; i < n; i++)
        if (m.ContainsKey(B[i]) && m[B[i]] == 1)
            res.Add(B[i]);
   
    // print result
    for(int i = 0; i < n; i++)
        Console.Write(res[i] + " ");
}
   
// Driver Code
static public void Main()
{
    int[] A = { 9, 7, 2, 3, 6 };
    int[] B = { 7, 4, 8, 0, 1 };
    int n = A.Length;
     
    maximizeTheFirstArray(A, B, n);
}
}
 
// This code is contributed by avanitrachhadiya2155


Javascript




<script>
// Make a set of maximum elements from two
// arrays A[] and B[]
function maximizeTheFirstArray(A, B, n)
{
 
    // Create copies of A[] and B[] and sort
    // the copies in descending order.
    let temp1 = new Array();
    let temp2 = new Array();
    for (let i of A)
    {
        temp1.push(i);
    }
    for (let i of B)
    {
        temp2.push(i);
    }
    temp1.sort((a, b) => a - b).reverse();
    temp2.sort((a, b) => a - b).reverse();
 
 
    // set maximum n distinct elements of
    // both sorted arrays in a map.
    let m = new Map();
    let i = 0, j = 0;
    while (m.size < n) {
        if (temp1[i] >= temp2[j]) {
            if (m.has(temp1[i])) {
                m.set(temp1[i], m.get(temp1[i]) + 1);
            }
            else {
                m.set(temp1[i], 1);
            }
            i++;
        }
        else {
            if (m.has(temp2[j])) {
                m.set(temp2[j], m.get(temp2[j]) + 1);
            }
            else {
                m.set(temp2[j], 1);
            }
            j++;
        }
    }
 
    // Copy elements of A[] to that
    // are present in hash m.
    let res = new Array();
    for (i = 0; i < n; i++)
        if (m.has(A[i]))
            res.push(A[i]);
 
    // Copy elements of B[] to that
    // are present in hash m. This time
    // we also check if the element did
    // not appear twice.
    for (i = 0; i < n; i++)
        if (m.has(B[i]) && m.get(B[i]) == 1)
            res.push(B[i]);
 
    // print result
    for (i = 0; i < n; i++)
        document.write(res[i] + " ");
}
 
// Driver program
let A = [9, 7, 2, 3, 6];
let B = [7, 4, 8, 0, 1];
let n = A.length;
maximizeTheFirstArray(A, B, n);
 
// This code is contributed by gfgking
 
</script>


Output

9 7 6 4 8 

Time complexity: O(n Log n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

C++ Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1-&gt;4-&gt;3-
4 min read
Java Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1-&gt;4-&gt;3-
4 min read
Python Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1-&gt;4-&gt;3-
4 min read
Javascript Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1-&gt;4-&gt;3-
4 min read
Partitioning a linked list around a given value and keeping the original order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place. Examples: Input : 1-&gt;4-&gt;3
15 min read
Minimize Array Sum by replacing pairs with (X, Y) keeping their bitwise OR same
Given an array arr[] of size N. Find the minimum sum of the array after performing given operations any number of times: Select two different indices i, j (1 ≤ i &lt; j ≤ N),Replace arr[i] and arr[j] with X and Y respectively (X, Y&gt;0), such that arr[i] | arr[j] = X | Y, where | denotes the bitwise OR operation Examples: Input: arr[] = {1, 3, 2}O
5 min read
Remove duplicates from string keeping the order according to last occurrences
Given a string, remove duplicate characters from the string, retaining the last occurrence of the duplicate characters. Assume the characters are case-sensitive. Examples: Input : geeksforgeeks Output : forgeks Explanation : Please note that we keep only last occurrences of repeating characters in same order as they appear in input. If we see resul
8 min read
Maximize distinct elements by incrementing/decrementing an element or keeping it same
Given an array arr[] of N elements, the task is to maximize the count of distinct elements in the array, by either of the given operation on each element of the array: either increasing the element by 1or decreasing the element by 1or keeping the element as it is. Note: No element can be less than or equal to 0. Examples: Input: arr = [4, 4, 5, 5,
6 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Practice Tags :
three90RightbarBannerImg