Maximize elements using another array in C++


Problem statement

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 i.e. all elements of the second array appear before the first array. The order of appearance of elements should be kept the same in output as in input

If arr1[] = {12, 15, 10} and arr2[] = {16, 17, 5} then {16, 17, 15} are the maximum elements from both array by maintaining order.

Algorithm

1. Create temporary array of size 2 * n
2. Store elements of arr1 and arr2 in temporary array and sort it in descending order
3. To keep the order of elements according to input arrays we will use hash table
4. Store first n largest unique elements of temporary array in hash table
5. Traverse the second array and store that elements of second array in temporary array that are present in hash table
6. Similarly, traverse the first array and store the elements that are present in hash table
7. In this way we get n unique and largest elements from both the arrays in temporary array

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printArray(int *arr, int n){
   for (int i = 0; i < n; ++i) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
bool compare(int a, int b){
   return a > b;
}
void getMaxElements(int *arr1, int *arr2, int n){
   int temp[2 * n];
   int k = 0;
   for (int i = 0; i < n; ++i) {
      temp[k] = arr1[i];
      ++k;
   }
   for (int i = 0; i < n; ++i) {
      temp[k] = arr2[i];
      ++k;
   }
   sort(temp, temp + 2 * n, compare);
   unordered_set<int> hash;
   int i = 0;
   while (hash.size() != n) {
      if (hash.find(temp[i]) == hash.end()) {
         hash.insert(temp[i]);
      }
      ++i;
   }
   k = 0;
   for (int i = 0; i < n; ++i) {
      if (hash.find(arr2[i]) != hash.end()) {
         temp[k++] = arr2[i];
         hash.erase(arr2[i]);
      }
   }
   for (int i = 0; i < n; ++i) {
      if (hash.find(arr1[i]) != hash.end()) {
         temp[k++] == arr1[i];
         hash.erase(arr1[i]);
      }
   }
   for (int i = 0; i < n; ++i) {
      arr1[i] = temp[i];
   }
}
int main(){
   int arr1[] = {12, 15, 10};
   int arr2[] = {16, 17, 5};
   int n = sizeof(arr1) / sizeof(arr1[0]);
   cout << "First array:\n";
   printArray(arr1, n);
   cout << "Second array:\n";
   printArray(arr2, n);
   getMaxElements(arr1, arr2, n);
   cout << "Maximum array:\n";
   printArray(arr1, n);
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

First array:
12 15 10
Second array:
16 17 5
Maximum array:
16 17 15

Updated on: 24-Dec-2019

802 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements