Maximize elements using another array
Last Updated :
27 Apr, 2025
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(" "));
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);
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem