Maximum array from two given arrays keeping order same
Given two same-sized arrays a[] and b[] (each containing distinct elements individually, but they may have some common elements between them). The task is to create a third array res[] of the same size n that includes maximum n elements combined from both arrays.
Start by including elements from a[] (in the same order), followed by elements from b[] (also in order). If an element is common in both arrays, it should appear only once in res[], and priority should be given to a[].
Examples:
Input: a[] = [9, 7, 2, 3, 6], b[] = [7, 4, 8, 0, 1]
Output: [9, 7, 6, 4, 8]
Explanation: Start with elements from a[]: 9, 7, 2, 3, 6. Remove duplicates later if they appear again in b[] (7 is already taken). Now consider b[]: skip 7 (already added), then take 4 and 8. Stop once we have 5 unique elements.Input: a[] = [6, 7, 5, 3], b[] = [5, 6, 2, 9]
Output: [6, 7, 5, 9]
Explanation: Start with elements from a[]: 6, 7, 5, 3. We now have 4 elements, but we skip 3 to allow space for unique ones from b[]. From b[], skip 5 and 6 (already taken), then take 9. Now we have 4 unique elements in total.
Approach:
The idea is to collect top n unique elements from both arrays using sorting and a map. We first pick from a[], then from b[] (only if not repeated), preserving original order.
Steps to implement the above idea:
- Copy a[] and b[] into temporary arrays and sort them in descending order separately.
- Use a hash map to store unique elements, adding from the sorted arrays until its size reaches n.
- Initialize an empty result array to store the final answer in correct order.
- Traverse a[] and push elements into result if they exist in the map.
- Traverse b[] and push elements if they are in the map and not already used.
- Finally, return the result array containing the selected values from a[] and b[].
// C++ program to maximize elements using maximum
// unique elements from a[] and b[]
#include <bits/stdc++.h>
using namespace std;
// Function to return result vector
// with max elements
vector<int> maximizeTheFirstArray(vector<int> &a,
vector<int> &b) {
int n = a.size();
// Copy and sort both arrays in descending order
vector<int> temp1 = a;
vector<int> temp2 = b;
sort(temp1.begin(), temp1.end(), greater<int>());
sort(temp2.begin(), temp2.end(), greater<int>());
// Store top 'n' unique elements from both arrays
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> res;
// Add elements from a[] if present in map
for (int i = 0; i < n; i++) {
if (m.find(a[i]) != m.end()) {
res.push_back(a[i]);
}
}
// Add elements from b[] if present and not repeated
for (int i = 0; i < n; i++) {
if (m.find(b[i]) != m.end() && m[b[i]] == 1) {
res.push_back(b[i]);
}
}
return res;
}
// Function to print elements of a vector
void printArray(vector<int> &res) {
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
}
// Driver code
int main() {
vector<int> a = {9, 7, 2, 3, 6};
vector<int> b = {7, 4, 8, 0, 1};
vector<int> result = maximizeTheFirstArray(a, b);
printArray(result);
return 0;
}
// Java program to maximize elements using maximum
// unique elements from a[] and b[]
import java.util.*;
class GfG {
// Function to return result array
// with max elements
static int[] maximizeTheFirstArray(int[] a, int[] b) {
int n = a.length;
// Copy and sort both arrays in descending order
Integer[] temp1 = Arrays.stream(a).boxed().toArray(Integer[]::new);
Integer[] temp2 = Arrays.stream(b).boxed().toArray(Integer[]::new);
Arrays.sort(temp1, Collections.reverseOrder());
Arrays.sort(temp2, Collections.reverseOrder());
// Store top 'n' unique elements from both arrays
HashMap<Integer, Integer> m = new HashMap<>();
int i = 0, j = 0;
while (m.size() < n) {
if (temp1[i] >= temp2[j]) {
m.put(temp1[i], m.getOrDefault(temp1[i], 0) + 1);
i++;
} else {
m.put(temp2[j], m.getOrDefault(temp2[j], 0) + 1);
j++;
}
}
List<Integer> res = new ArrayList<>();
// Add elements from a[] if present in map
for (i = 0; i < n; i++) {
if (m.containsKey(a[i])) {
res.add(a[i]);
}
}
// Add elements from b[] if present and not repeated
for (i = 0; i < n; i++) {
if (m.containsKey(b[i]) && m.get(b[i]) == 1) {
res.add(b[i]);
}
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
// Function to print elements of an array
static void printArray(int[] res) {
for (int val : res) {
System.out.print(val + " ");
}
System.out.println();
}
// Driver code
public static void main(String[] args) {
int[] a = {9, 7, 2, 3, 6};
int[] b = {7, 4, 8, 0, 1};
int[] result = maximizeTheFirstArray(a, b);
printArray(result);
}
}
# Python program to maximize elements using maximum
# unique elements from a[] and b[]
# Function to return result list
# with max elements
def maximizeTheFirstArray(a, b):
n = len(a)
# Copy and sort both arrays in descending order
temp1 = sorted(a, reverse=True)
temp2 = sorted(b, reverse=True)
# Store top 'n' unique elements from both arrays
m = {}
i = j = 0
while len(m) < n:
if temp1[i] >= temp2[j]:
m[temp1[i]] = m.get(temp1[i], 0) + 1
i += 1
else:
m[temp2[j]] = m.get(temp2[j], 0) + 1
j += 1
res = []
# Add elements from a[] if present in map
for i in range(n):
if a[i] in m:
res.append(a[i])
# Add elements from b[] if present and not repeated
for i in range(n):
if b[i] in m and m[b[i]] == 1:
res.append(b[i])
return res
# Function to print elements of a list
def printArray(res):
for val in res:
print(val, end=' ')
print()
# Driver code
if __name__ == "__main__":
a = [9, 7, 2, 3, 6]
b = [7, 4, 8, 0, 1]
result = maximizeTheFirstArray(a, b)
printArray(result)
// C# program to maximize elements using maximum
// unique elements from a[] and b[]
using System;
using System.Collections.Generic;
class GfG {
// Function to return result list
// with max elements
static List<int> maximizeTheFirstArray(int[] a, int[] b) {
int n = a.Length;
// Copy and sort both arrays in descending order
List<int> temp1 = new List<int>(a);
List<int> temp2 = new List<int>(b);
temp1.Sort((x, y) => y.CompareTo(x));
temp2.Sort((x, y) => y.CompareTo(x));
// Store top 'n' unique elements from both arrays
Dictionary<int, int> m = new Dictionary<int, int>();
int i = 0, j = 0;
while (m.Count < n) {
if (temp1[i] >= temp2[j]) {
if (!m.ContainsKey(temp1[i])) m[temp1[i]] = 0;
m[temp1[i]]++;
i++;
} else {
if (!m.ContainsKey(temp2[j])) m[temp2[j]] = 0;
m[temp2[j]]++;
j++;
}
}
List<int> res = new List<int>();
// Add elements from a[] if present in map
for (i = 0; i < n; i++) {
if (m.ContainsKey(a[i])) {
res.Add(a[i]);
}
}
// Add elements from b[] if present and not repeated
for (i = 0; i < n; i++) {
if (m.ContainsKey(b[i]) && m[b[i]] == 1) {
res.Add(b[i]);
}
}
return res;
}
// Function to print elements of a list
static void printArray(List<int> res) {
foreach (int val in res) {
Console.Write(val + " ");
}
Console.WriteLine();
}
// Driver code
public static void Main() {
int[] a = {9, 7, 2, 3, 6};
int[] b = {7, 4, 8, 0, 1};
List<int> result = maximizeTheFirstArray(a, b);
printArray(result);
}
}
// JavaScript program to maximize elements using maximum
// unique elements from a[] and b[]
// Function to return result array
// with max elements
function maximizeTheFirstArray(a, b) {
let n = a.length;
// Copy and sort both arrays in descending order
let temp1 = [...a].sort((x, y) => y - x);
let temp2 = [...b].sort((x, y) => y - x);
// Store top 'n' unique elements from both arrays
let m = new Map();
let i = 0, j = 0;
while (m.size < n) {
if (temp1[i] >= temp2[j]) {
m.set(temp1[i], (m.get(temp1[i]) || 0) + 1);
i++;
} else {
m.set(temp2[j], (m.get(temp2[j]) || 0) + 1);
j++;
}
}
let res = [];
// Add elements from a[] if present in map
for (i = 0; i < n; i++) {
if (m.has(a[i])) {
res.push(a[i]);
}
}
// Add elements from b[] if present and not repeated
for (i = 0; i < n; i++) {
if (m.has(b[i]) && m.get(b[i]) === 1) {
res.push(b[i]);
}
}
return res;
}
// Function to print elements of an array
function printArray(res) {
console.log(res.join(" "));
}
// Driver code
let a = [9, 7, 2, 3, 6];
let b = [7, 4, 8, 0, 1];
let result = maximizeTheFirstArray(a, b);
printArray(result);
Output
9 7 6 4 8
Time complexity: O(n*log(n)), as sorting both arrays takes O(n*log(n)), traversal adds another O(n) time.
Auxiliary Space: O(n), as we use extra space for storing sorted arrays and map.