Maximum array from two given arrays keeping order same in C++

C++Server Side ProgrammingProgramming

Problem statement

Given two same sized arrays A[] and B[]. Task is to form a third array of same size. The result array should have maximum n elements from both array. It should have chosen elements of A[] first, then chosen elements of B[] in same order as they appear in original arrays. If there are common elements, then only one element should be present in res[] and priority should be given to A[]

Example

If input arrays are −

arr1[] = {9, 17, 2, 25, 6}
arr2[] = {17, 4, 8, 10, 1} then final array is:
{9, 17, 25, 8, 10}

Please note that element 17 is common and priority is given to the arr1

Algorithm

  • Create copies of both arrays and sort the copies in descending order
  • Use a hash to pick unique n maximum elements of both arrays, giving priority to arr1[]
  • Initialize result array as empty
  • Traverse through arr1[], copy those elements of arr1[] that are present in the hash. This is done to keep order of elements same
  • Repeat step 4 for arr2[]. This time we only consider those elements that are not present in arr1[]

Example

Let us now see an example −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printArray(vector<int> &arr, int n) {
   for (int i = 0; i < n; ++i) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
void getMaxArray(int *arr1, int *arr2, int n) {
   vector<int> temp1(arr1, arr1 + n); vector<int> temp2(arr2, arr2 + n);
   sort(temp1.begin(), temp1.end(), greater<int>()); sort(temp2.begin(), temp2.end(), greater<int>());
   unordered_map<int, int> m;
   int i = 0, j = 0;
   while (m.size() < n) {
      if (temp1[i] >= temp2[j]) {
         m[temp1[i]]++;
         ++i;
      } else {
         m[temp2[j]]++;
         ++j;
      }
   }
   vector<int> result;
   for (int i = 0; i < n; ++i) {
      if (m.find(arr1[i]) != m.end()) {
         result.push_back(arr1[i]);
      }
   }
   for (int i = 0; i < n; ++i) {
      if (m.find(arr2[i]) != m.end() && m[arr2[i]] ==1) {
         result.push_back(arr2[i]);
      }
   }
   cout << "Final array:\n";
   printArray(result, n);
}
int main() {
   int arr1[] = {9, 17, 2, 25, 6};
   int arr2[] = {17, 4, 8, 10, 1};
   int n = sizeof(arr1) / sizeof(arr1[0]);
   getMaxArray(arr1, arr2, n);
   return 0;
}

Output

Final array:
9 17 25 8 10
raja
Published on 31-Dec-2019 16:38:35
Advertisements