Minimize product of maximum numbers in two Array using swaps
Given 2 arrays arr1[] and arr2[] of size N the task is to find the minimum product of maximums of both arrays by performing a swapping operation any number of times. In one swap operation, any index of the array is selected and arr1[index] and arr2[index] are swapped.
Examples:
Input: N = 2, arr1[2] = [1, 3], arr2[2] = [4, 1]
Output: 4
Explanation: Taking index = 1, swapping the arrays values, arr1 becomes, arr1[2] = [1. 1] and arr[2] = [4. 3]. Maximum of arr1 = 1 and maximum of arr2 = 4. Max(arr1)*Max(arr2) = 1*4 = 4.Input: N = 6, arr1[6] = [1, 2, 6, 5, 1, 1], arr2[6] = [3, 4, 3, 2, 2, 4]
Output: 18
Approach: The task can be solved using pointers and sorting. Follow the below steps to solve the problem:
- Run a loop from index = 0 to index = n -1
- If arr1[index] < arr2[index] swap these values .
- In the end, sort the two arrays, and get arr1[n-1]*arr2[n-1] as the required answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum productvoid minimumArrayProduct(int arr1[], int arr2[], int n){ // Iterate over the array and perform the swap // operations for (int index = 0; index < n; index++) { if (arr1[index] < arr2[index]) { swap(arr1[index], arr2[index]); } } // Sort the given arrays sort(arr1, arr1 + n); sort(arr2, arr2 + n); int ans = arr1[n - 1] * arr2[n - 1]; cout << ans << "\n";} // Driver Codeint main(){ int n = 2; int arr1[2] = { 1, 3 }; int arr2[2] = { 4, 1 }; minimumArrayProduct(arr1, arr2, n);} |
4
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Efficient Approach: Minimize product of maximum numbers in two Array using swaps | Set 2


.png)