Open In App

Maximize elements using another array

Last Updated : 27 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays a[] and b[] of size n. The task is to maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first array). The order of appearance of elements is kept same in output as in input.

Examples:

Input: a[] = [2, 4, 3] , b[] = [5, 6, 1] 
Output: 5 6 4 
Explanation: As 5, 6 and 4 are maximum elements from two arrays giving second array higher priority. Order of elements is same in output as in input.

Input: a[] = [7, 4, 8, 0, 1] , b[] = [9, 10, 2, 3, 6] 
Output: 9 10 6 7 8
Explanation: As 9, 7, 6, 4 and 8 are maximum elements from two arrays giving second array higher priority. Order of elements is same in output as in input.

Using Sorting – O(n log n) Time and O(n) Space

The idea is to first concatenate both arrays, then sort them in descending order to easily pick the largest elements. Using a hash set, we extract the n largest unique elements. Finally, we maintain the relative order of elements, first from b[], then from a[], to construct the result.

C++
// C++ program to maximize array elements
// giving second array higher priority
#include <bits/stdc++.h>
using namespace std;

// Compare function to sort elements
// in decreasing order
bool compare(int x, int y) {
    return x > y;
}

// Function to maximize array elements
vector<int> maximizeArray(vector<int>& a, 
                           vector<int>& b) {
    
    int n = a.size();
    
    // Auxiliary vector to store 
    // elements of a and b
    vector<int> merged(2 * n);
    
    int k = 0;

    // Copy elements from both arrays into merged
    for (int i = 0; i < n; i++) {
        merged[k++] = a[i];
    }
    for (int i = 0; i < n; i++) {
        merged[k++] = b[i];
    }

    // Hash set to store n largest
    // unique elements
    unordered_set<int> hash;

    // Sorting merged array in decreasing order
    sort(merged.begin(), merged.end(), compare);

    // Finding n largest unique elements 
    // and storing in hash
    int i = 0;
    while (hash.size() < n) {

        // If the element is not in hash, insert it
        if (hash.find(merged[i]) == hash.end()) {
            hash.insert(merged[i]);
        }
        
        i++;
    }

    vector<int> result;
    
    // Store elements of b in result that
    // are present in hash
    for (int i = 0; i < n; i++) {
        if (hash.find(b[i]) != hash.end()) {
            result.push_back(b[i]);
            hash.erase(b[i]);
        }
    }

    // Store elements of a in result that
    // are present in hash
    for (int i = 0; i < n; i++) {
        if (hash.find(a[i]) != hash.end()) {
            result.push_back(a[i]);
            hash.erase(a[i]);
        }
    }

    return result;
}


// Driver Code
int main() {

    // Input arrays
    vector<int> a = {7, 4, 8, 0, 1};
    vector<int> b = {9, 7, 2, 3, 6};

    vector<int> res = maximizeArray(a, b);

    for (int num : res) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
Java
// Java program to maximize array elements
// giving second array higher priority
import java.util.*;

class GfG {

    // Compare function to sort elements
    // in decreasing order
    static Comparator<Integer> compare = 
                    (x, y) -> Integer.compare(y, x);

    // Function to maximize array elements
    static int[] maximizeArray(int[] a, int[] b) {
        
        int n = a.length;

        // Auxiliary array to store 
        // elements of a and b
        int[] merged = new int[2 * n];

        int k = 0;

        // Copy elements from both arrays into merged
        for (int i = 0; i < n; i++) {
            merged[k++] = a[i];
        }
        for (int i = 0; i < n; i++) {
            merged[k++] = b[i];
        }

        // Hash set to store n largest
        // unique elements
        Set<Integer> hash = new HashSet<>();

        // Sorting merged array in decreasing order
        Arrays.sort(merged);
        Integer[] temp = Arrays.stream(merged)
                               .boxed()
                               .toArray(Integer[]::new);
        Arrays.sort(temp, compare);

        // Finding n largest unique elements 
        // and storing in hash
        int i = 0;
        while (hash.size() < n) {

            // If the element is not in hash, insert it
            if (!hash.contains(temp[i])) {
                hash.add(temp[i]);
            }

            i++;
        }

        int[] result = new int[n];
        k = 0;

        // Store elements of b in result that
        // are present in hash
        for (int x : b) {
            if (hash.contains(x)) {
                result[k++] = x;
                hash.remove(x);
            }
        }

        // Store elements of a in result that
        // are present in hash
        for (int x : a) {
            if (hash.contains(x)) {
                result[k++] = x;
                hash.remove(x);
            }
        }

        return result;
    }

    // Function to print array elements
    static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        int[] a = {7, 4, 8, 0, 1};
        int[] b = {9, 7, 2, 3, 6};

        int[] result = maximizeArray(a, b);

        printArray(result);
    }
}
Python
# Python program to maximize array elements
# giving second array higher priority

# Function to maximize array elements
def maximizeArray(a, b):
    
    n = len(a)
    
    # Auxiliary list to store elements of a and b
    merged = a + b

    # Hash set to store n largest unique elements
    hash_set = set()

    # Sorting merged array in decreasing order
    merged.sort(reverse=True)

    # Finding n largest unique elements 
    # and storing in hash_set
    i = 0
    while len(hash_set) < n:
        
        # If the element is not in hash_set, insert it
        if merged[i] not in hash_set:
            hash_set.add(merged[i])
        
        i += 1

    result = []

    # Store elements of b in result that
    # are present in hash_set
    for x in b:
        if x in hash_set:
            result.append(x)
            hash_set.remove(x)

    # Store elements of a in result that
    # are present in hash_set
    for x in a:
        if x in hash_set:
            result.append(x)
            hash_set.remove(x)

    return result

# Function to print array elements
def printArray(arr):
    print(" ".join(map(str, arr)))

# Driver Code
if __name__ == "__main__":

    # Input arrays
    a = [7, 4, 8, 0, 1]
    b = [9, 7, 2, 3, 6]

    result = maximizeArray(a, b)

    printArray(result)
C#
// C# program to maximize array elements
// giving second array higher priority
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {

    // Compare function to sort elements
    // in decreasing order
    static int Compare(int x, int y) {
        return y.CompareTo(x);
    }

    // Function to maximize array elements
    static int[] maximizeArray(int[] a, int[] b) {
        
        int n = a.Length;

        // Auxiliary array to store 
        // elements of a and b
        int[] merged = new int[2 * n];

        int k = 0;

        // Copy elements from both arrays into merged
        for (int i = 0; i < n; i++) {
            merged[k++] = a[i];
        }
        for (int i = 0; i < n; i++) {
            merged[k++] = b[i];
        }

        // Hash set to store n largest
        // unique elements
        HashSet<int> hash = new HashSet<int>();

        // Sorting merged array in decreasing order
        Array.Sort(merged);
        Array.Reverse(merged);

        // Finding n largest unique elements 
        // and storing in hash
        int j = 0;
        while (hash.Count < n) {

            // If the element is not in hash, insert it
            if (!hash.Contains(merged[j])) {
                hash.Add(merged[j]);
            }

            j++;
        }

        int[] result = new int[n];
        k = 0;

        // Store elements of b in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.Contains(b[i])) {
                result[k++] = b[i];
                hash.Remove(b[i]);
            }
        }

        // Store elements of a in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.Contains(a[i])) {
                result[k++] = a[i];
                hash.Remove(a[i]);
            }
        }

        return result;
    }

    // Function to print array elements
    static void printArray(int[] arr) {
        Console.WriteLine(string.Join(" ", arr));
    }

    // Driver Code
    public static void Main() {

        // Input arrays
        int[] a = {7, 4, 8, 0, 1};
        int[] b = {9, 7, 2, 3, 6};

        int[] result = maximizeArray(a, b);

        printArray(result);
    }
}
JavaScript
// JavaScript program to maximize array elements
// giving second array higher priority

// Function to maximize array elements
function maximizeArray(a, b) {
    
    let n = a.length;

    // Auxiliary array to store elements of a and b
    let merged = [...a, ...b];

    // Hash set to store n largest unique elements
    let hashSet = new Set();

    // Sorting merged array in decreasing order
    merged.sort((x, y) => y - x);

    // Finding n largest unique elements 
    // and storing in hashSet
    let i = 0;
    while (hashSet.size < n) {

        // If the element is not in hashSet, insert it
        if (!hashSet.has(merged[i])) {
            hashSet.add(merged[i]);
        }
        
        i++;
    }

    let result = [];

    // Store elements of b in result that
    // are present in hashSet
    for (let x of b) {
        if (hashSet.has(x)) {
            result.push(x);
            hashSet.delete(x);
        }
    }

    // Store elements of a in result that
    // are present in hashSet
    for (let x of a) {
        if (hashSet.has(x)) {
            result.push(x);
            hashSet.delete(x);
        }
    }

    return result;
}

// Driver Code
let a = [7, 4, 8, 0, 1];
let b = [9, 7, 2, 3, 6];

console.log(maximizeArray(a, b).join(" "));

Output
9 7 6 4 8

Using Priority Queue – O(n log n) Time and O(n) Space

The idea is to use a priority queue. We push all elements into a max heap to efficiently extract the top n unique values. A hash set ensures uniqueness, and the result is constructed by preserving order from b[] first, then a[].

C++
// C++ program to maximize array elements
// using priority queue for efficient selection
#include <bits/stdc++.h>
using namespace std;

// Function to maximize array elements
vector<int> maximizeArray(vector<int>& a, 
                           vector<int>& b) {
    
    int n = a.size();
    
    // Max heap to store elements in 
    // decreasing order
    priority_queue<int> pq;
    
    // Hash set to ensure unique elements
    unordered_set<int> hash;

    // Insert all elements from a and b 
    // into max heap
    for (int i = 0; i < n; i++) {
        pq.push(a[i]);
        pq.push(b[i]);
    }

    // Extract n largest unique elements
    vector<int> largest;
    while (!pq.empty() && largest.size() < n) {
        int top = pq.top();
        pq.pop();

        if (hash.find(top) == hash.end()) {
            hash.insert(top);
            largest.push_back(top);
        }
    }

    vector<int> result;
    
    // Store elements of b in result that
    // are present in hash
    for (int i = 0; i < n; i++) {
        if (hash.find(b[i]) != hash.end()) {
            result.push_back(b[i]);
            hash.erase(b[i]);
        }
    }

    // Store elements of a in result that
    // are present in hash
    for (int i = 0; i < n; i++) {
        if (hash.find(a[i]) != hash.end()) {
            result.push_back(a[i]);
            hash.erase(a[i]);
        }
    }

    return result;
}

// Function to print array elements
void printArray(vector<int>& arr) {
    for (int num : arr) {
        cout << num << " ";
    }
    cout << endl;
}

// Driver Code
int main() {

    vector<int> a = {7, 4, 8, 0, 1};
    vector<int> b = {9, 7, 2, 3, 6};

    vector<int> result = maximizeArray(a, b);

    printArray(result);

    return 0;
}
Java
// Java program to maximize array elements
// using priority queue for efficient selection
import java.util.*;

class GfG {

    // Function to maximize array elements
    static int[] maximizeArray(int[] a, int[] b) {

        int n = a.length;

        // Max heap to store elements in 
        // decreasing order
        PriorityQueue<Integer> pq = 
            new PriorityQueue<>(Collections.reverseOrder());

        // Hash set to ensure unique elements
        HashSet<Integer> hash = new HashSet<>();

        // Insert all elements from a and b 
        // into max heap
        for (int i = 0; i < n; i++) {
            pq.add(a[i]);
            pq.add(b[i]);
        }

        // Extract n largest unique elements
        List<Integer> largest = new ArrayList<>();
        while (!pq.isEmpty() && largest.size() < n) {
            int top = pq.poll();

            if (!hash.contains(top)) {
                hash.add(top);
                largest.add(top);
            }
        }

        int[] result = new int[n];
        int k = 0;

        // Store elements of b in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.contains(b[i])) {
                result[k++] = b[i];
                hash.remove(b[i]);
            }
        }

        // Store elements of a in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.contains(a[i])) {
                result[k++] = a[i];
                hash.remove(a[i]);
            }
        }

        return result;
    }

    // Function to print array elements
    static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {

        // Input arrays
        int[] a = {7, 4, 8, 0, 1};
        int[] b = {9, 7, 2, 3, 6};

        int[] result = maximizeArray(a, b);

        printArray(result);
    }
}
Python
# Python program to maximize array elements
# using priority queue for efficient selection
import heapq

# Function to maximize array elements
def maximizeArray(a, b):
    
    n = len(a)
    
    # Max heap to store elements in 
    # decreasing order
    pq = []
    
    # Hash set to ensure unique elements
    hash_set = set()

    # Insert all elements from a and b 
    # into max heap
    for i in range(n):
        heapq.heappush(pq, -a[i])
        heapq.heappush(pq, -b[i])

    # Extract n largest unique elements
    largest = []
    while pq and len(largest) < n:
        top = -heapq.heappop(pq)

        if top not in hash_set:
            hash_set.add(top)
            largest.append(top)

    result = []
    
    # Store elements of b in result that
    # are present in hash
    for i in range(n):
        if b[i] in hash_set:
            result.append(b[i])
            hash_set.remove(b[i])

    # Store elements of a in result that
    # are present in hash
    for i in range(n):
        if a[i] in hash_set:
            result.append(a[i])
            hash_set.remove(a[i])

    return result

# Function to print array elements
def printArray(arr):
    print(" ".join(map(str, arr)))

# Driver Code
if __name__ == "__main__":

    # Input arrays
    a = [7, 4, 8, 0, 1]
    b = [9, 7, 2, 3, 6]

    result = maximizeArray(a, b)

    printArray(result)
C#
// C# program to maximize array elements
// using priority queue for efficient selection
using System;
using System.Collections.Generic;

class GfG {

    // Custom Priority Queue (Max Heap)
    class PriorityQueue {
        private List<int> data = new List<int>();

        // Insert element in heap
        public void Enqueue(int val) {
            data.Add(val);
            
            // Sort in descending order
            data.Sort((x, y) => y.CompareTo(x)); 
        }

        // Remove and return the max element
        public int Dequeue() {
            int top = data[0];
            data.RemoveAt(0);
            return top;
        }

        // Get the number of elements in the heap
        public int Count() {
            return data.Count;
        }
    }

    // Function to maximize array elements
    static int[] maximizeArray(int[] a, int[] b) {

        int n = a.Length;

        // Max heap to store elements in 
        // decreasing order
        PriorityQueue pq = new PriorityQueue();

        // Hash set to ensure unique elements
        HashSet<int> hash = new HashSet<int>();

        // Insert all elements from a and b 
        // into max heap
        for (int i = 0; i < n; i++) {
            pq.Enqueue(a[i]);
            pq.Enqueue(b[i]);
        }

        // Extract n largest unique elements
        List<int> largest = new List<int>();
        while (pq.Count() > 0 && largest.Count < n) {
            int top = pq.Dequeue();

            if (!hash.Contains(top)) {
                hash.Add(top);
                largest.Add(top);
            }
        }

        int[] result = new int[n];
        int k = 0;

        // Store elements of b in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.Contains(b[i])) {
                result[k++] = b[i];
                hash.Remove(b[i]);
            }
        }

        // Store elements of a in result that
        // are present in hash
        for (int i = 0; i < n; i++) {
            if (hash.Contains(a[i])) {
                result[k++] = a[i];
                hash.Remove(a[i]);
            }
        }

        return result;
    }

    // Function to print array elements
    static void printArray(int[] arr) {
        Console.WriteLine(string.Join(" ", arr));
    }

    // Driver Code
    public static void Main() {

        // Input arrays
        int[] a = {7, 4, 8, 0, 1};
        int[] b = {9, 7, 2, 3, 6};

        int[] result = maximizeArray(a, b);

        printArray(result);
    }
}
JavaScript
// JavaScript program to maximize array elements
// using priority queue for efficient selection

class PriorityQueue {
    constructor() {
        this.data = [];
    }

    push(val) {
        this.data.push(val);
        this.data.sort((x, y) => y - x);
    }

    pop() {
        return this.data.shift();
    }

    size() {
        return this.data.length;
    }
}

// Function to maximize array elements
function maximizeArray(a, b) {
    
    let n = a.length;
    
    // Max heap to store elements in 
    // decreasing order
    let pq = new PriorityQueue();
    
    // Hash set to ensure unique elements
    let hash = new Set();

    // Insert all elements from a and b 
    // into max heap
    for (let i = 0; i < n; i++) {
        pq.push(a[i]);
        pq.push(b[i]);
    }

    // Extract n largest unique elements
    let largest = [];
    while (pq.size() > 0 && largest.length < n) {
        let top = pq.pop();

        if (!hash.has(top)) {
            hash.add(top);
            largest.push(top);
        }
    }

    let result = [];
    
    // Store elements of b in result that
    // are present in hash
    for (let i = 0; i < n; i++) {
        if (hash.has(b[i])) {
            result.push(b[i]);
            hash.delete(b[i]);
        }
    }

    // Store elements of a in result that
    // are present in hash
    for (let i = 0; i < n; i++) {
        if (hash.has(a[i])) {
            result.push(a[i]);
            hash.delete(a[i]);
        }
    }

    return result;
}

// Function to print array elements
function printArray(arr) {
    console.log(arr.join(" "));
}

// Driver Code
let a = [7, 4, 8, 0, 1];
let b = [9, 7, 2, 3, 6];

let result = maximizeArray(a, b);

printArray(result);

Output
9 7 6 4 8 


Next Article
Article Tags :
Practice Tags :

Similar Reads