Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
C++ Program to Find the Minimum and Maximum Element of an Array
Next article icon

C++ Program to Maximize elements using another array

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays with size n, 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 : arr1[] = {2, 4, 3} 
arr2[] = {5, 6, 1} 
Output : 5 6 4 
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 : arr1[] = {7, 4, 8, 0, 1} 
arr2[] = {9, 7, 2, 3, 6} 
Output : 9 7 6 4 8


Approach : We create an auxiliary array of size 2*n and store the elements of 2nd array in auxiliary array, and then we will store elements of 1st array in it. After that we will sort auxiliary array in decreasing order. To keep the order of elements according to input arrays we will use hash table. We will store 1st n largest unique elements of auxiliary array in hash table. Now we traverse the second array and store that elements of second array in auxiliary array that are present in hash table. Similarly we will traverse first array and store the elements that are present in hash table. In this way we get n unique and largest elements from both the arrays in auxiliary array while keeping the order of appearance of elements same.

Below is the implementation of above approach :

C++
// C++ program to print the maximum elements // giving second array higher priority #include <bits/stdc++.h> using namespace std;  // Compare function used to sort array  // in decreasing order bool compare(int a, int b) {     return a > b; }  // Function to maximize array elements void maximizeArray(int arr1[], int arr2[],                                    int n) {     // auxiliary array arr3 to store      // elements of arr1 & arr2     int arr3[2*n], k = 0;     for (int i = 0; i < n; i++)          arr3[k++] = arr1[i];     for (int i = 0; i < n; i++)         arr3[k++] = arr2[i];      // hash table to store n largest     // unique elements     unordered_set<int> hash;      // sorting arr3 in decreasing order     sort(arr3, arr3 + 2 * n, compare);      // finding n largest unique elements     // from arr3 and storing in hash     int i = 0;     while (hash.size() != n) {          // if arr3 element not present in hash,         // then store this element in hash         if (hash.find(arr3[i]) == hash.end())              hash.insert(arr3[i]);                  i++;     }      // store that elements of arr2 in arr3     // that are present in hash     k = 0;     for (int i = 0; i < n; i++) {          // if arr2 element is present in hash,         // store it in arr3         if (hash.find(arr2[i]) != hash.end()) {             arr3[k++] = arr2[i];             hash.erase(arr2[i]);         }     }      // store that elements of arr1 in arr3     // that are present in hash     for (int i = 0; i < n; i++) {          // if arr1 element is present in hash,         // store it in arr3         if (hash.find(arr1[i]) != hash.end()) {             arr3[k++] = arr1[i];             hash.erase(arr1[i]);         }     }      // copying 1st n elements of arr3 to arr1     for (int i = 0; i < n; i++)          arr1[i] = arr3[i];     }  // Function to print array elements void printArray(int arr[], int n) {     for (int i = 0; i < n; i++)          cout << arr[i] << " ";         cout << endl; }  // Driver Code int main() {     int array1[] = { 7, 4, 8, 0, 1 };     int array2[] = { 9, 7, 2, 3, 6 };     int size = sizeof(array1) / sizeof(array1[0]);     maximizeArray(array1, array2, size);     printArray(array1, size); } 

Output: 
9 7 6 4 8

Time complexity: O(n * log n).
Space complexity: O(n) as array and set has been created.

Please refer complete article on Maximize elements using another array for more details!


Next Article
C++ Program to Find the Minimum and Maximum Element of an Array
author
kartik
Improve
Article Tags :
  • Sorting
  • Hash
  • C++ Programs
  • C++
  • DSA
  • Arrays
  • cpp-unordered_set
Practice Tags :
  • CPP
  • Arrays
  • Hash
  • Sorting

Similar Reads

  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • How to Find the Maximum Element of an Array using STL in C++?
    Given an array of n elements, the task is to find the maximum element using STL in C++. Examples Input: arr[] = {11, 13, 21, 45, 8}Output: 45Explanation: 45 is the largest element of the array. Input: arr[] = {1, 9, 2, 5, 7}Output: 9Explanation: 9 is the largest element of the array. STL provides th
    3 min read
  • C++ Program to Find the Minimum and Maximum Element of an Array
    Given an array, write functions to find the minimum and maximum elements in it.  Example: C/C++ Code // C++ program to find minimum (or maximum) element // in an array. #include <bits/stdc++.h> using namespace std; int getMin(int arr[], int n) { int res = arr[0]; for (int i = 1; i < n; i++)
    3 min read
  • Program to find largest element in an array using Dynamic Memory Allocation
    Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation. Examples: Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7. Input: arr[] = {8, 9, 10, 12} Output: 12Explanati
    5 min read
  • C++ Program for Maximum equilibrium sum in an array
    Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1} Output : 4 Prefix sum of arr[0..3] = Suffix sum of arr[3..6] Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2} Output : 7 Prefix sum of arr[0..3] = Su
    4 min read
  • C++ Program to Find the Second Largest Element in an Array
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
    3 min read
  • How to Find Minimum and Maximum Element of an Array Using STL in C++?
    Given an array of n elements, the task is to find the minimum and maximum element of array using STL in C++. Examples Input: arr[] = {1, 45, 54, 7, 76}Output: min = 1, max = 76Explanation: 1 is the smallest and 76 is the largest among all elements.Input: arr[] = {10, 7, 5, 4, 6}Output: min = 4, max
    3 min read
  • C++ Program to Find k maximum elements of array in original order
    Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
    3 min read
  • Maximize the rightmost element of an array in k operations in Linear Time
    Given an array arr[ ] of size N and an integer p, the task is to find maximum possible value of rightmost element of array arr[ ] performing at most k operations.In one operation decrease arr[i] by p and increase arr[i+1] by p. Examples: Input: N = 4, p = 2, k = 5, arr = {3, 8, 1, 4}Output: 8Explana
    9 min read
  • C++ Program to Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:   Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences