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++
Java Python C# JavaScript

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++
Java Python C# JavaScript

Output
9 7 6 4 8 


Next Article
Article Tags :
Practice Tags :

Similar Reads