VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-elements-using-another-array/

⇱ Maximum from Two Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum from Two Arrays

Last Updated : 20 May, 2026

Given two arrays a[] and b[] of size n. The task is to create an array the same size using the elements from both the arrays such that the new array formed contains n greatest but unique elements of both the arrays. The order of elements should follow the below rules.

  • 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 10, 9, 8, 7 and 6 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 merge both arrays and sort the merged array in decreasing order. Then store the n largest unique elements using a hash set. Finally, traverse b first and a next, and add elements to ans only if they are among the selected elements and are not already added. This maintains the required order and gives the maximum unique elements.


Output
9 10 6 7 8 

Time Complexity: O(n log n)
Auxiliary Space: O(n)

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

The idea is to use a max heap to store all elements of both arrays so that the largest elements can be accessed efficiently. Then store the n largest unique elements in a hash set. Finally, traverse b first and a next, and add elements to ans only if they belong to the selected elements and are not already added. This maintains the required order and gives the maximum unique elements.


Output
9 10 6 7 8 

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Comment
Article Tags: