The Wayback Machine - https://web.archive.org/web/20220202193136/https://www.geeksforgeeks.org/minimize-product-of-maximum-numbers-in-two-array-using-swaps-2/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize product of maximum numbers in two Array using swaps

  • Last Updated : 02 Feb, 2022

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:

  1. Run a loop from index = 0 to index = n -1
  2. If arr1[index] < arr2[index] swap these values .
  3. 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 product
void 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 Code
int main()
{
  
    int n = 2;
    int arr1[2] = { 1, 3 };
    int arr2[2] = { 4, 1 };
  
    minimumArrayProduct(arr1, arr2, n);
}
Output
4

Time Complexity: O(NlogN)
Auxiliary Space: O(N)

Efficient Approach: Minimize product of maximum numbers in two Array using swaps | Set 2


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!