Product of maximum in first array and minimum in second in C


Given two arrays arr1[] and arr2[] of some size n1 and n2 respectively, we have to find the product of maximum element of first array arr1[] and minimum element of the second array arr2[].

Like we have elements in arr1[] = {5, 1, 6, 8, 9} and in arr2[] = {2, 9, 8, 5, 3} so the maximum element in arr1 is 9 and the minimum element in arr2 is 2 so the product of both is 9*2 = 18, likewise we have to write a program to solve the given problem.

Input 

arr1[] = {6, 2, 5, 4, 1}
arr2[] = {3, 7, 5, 9, 6}

Output 

18

Explanation 

MAX(arr1) * MIN(arr2) → 6 * 3 = 18

Input 

arr1[] = { 2, 3, 9, 11, 1 }
arr2[] = { 5, 4, 2, 6, 9 }

Output 

22

Explanation 

MAX(arr1) * MIN(arr2) → 11 * 2 = 22

Approach used below is as follows to solve the problem

  • We will two arrays arr1 and arr2 as input

  • We will sort both the arrays in ascending order.

  • We will multiply the last element of arr1 (the maximum element) and the first element of arr2 (the minimum element).

  • Return the product.

Algorithm

Start
In function int sortarr(int arr[], int n)
   Step 1→ Declare and initialize temp
   Step 2→ For i = 0 and i < n-1 and ++i
      For j = i+1 and j<n and j++
         If arr[i]> arr[j] then,
         Set temp as arr[i]
         Set arr[i] as arr[j]
         Set arr[j] as temp
In Function int minMaxProduct(int arr1[], int arr2[], int n1, int n2)
   Step 1→ Call sortarr(arr1, n1)
   Step 2→ Call sortarr(arr2, n2)
   Step 3→ Return (arr1[n1 - 1] * arr2[0])
In Function int main()
   Step 1→ Declare and Initialize arr1[] = { 2, 3, 9, 11, 1 }
   Step 2→ Declare and Initialize arr2[] = { 5, 4, 2, 6, 9 }
   Step 3→ Declare and Initialize n1, n2 and initialize the size of both arrays
   Step 4→ Print minMaxProduct (arr1, arr2, n1, n2))
Stop

Example

 Live Demo

#include <stdio.h>
int sortarr(int arr[], int n){
   int temp;
   for (int i = 0; i < n-1; ++i){
      for(int j = i+1; j<n; j++){
         if(arr[i]> arr[j]){
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
         }
      }
   }
   return 0;
}
int minMaxProduct(int arr1[], int arr2[], int n1, int n2){
   // Sort the arrays to get
   // maximum and minimum
   sortarr(arr1, n1);
   sortarr(arr2, n2);
   // Return product of
   // maximum and minimum.
   return arr1[n1 - 1] * arr2[0];
}
int main(){
   int arr1[] = { 2, 3, 9, 11, 1 };
   int arr2[] = { 5, 4, 2, 6, 9 };
   int n1 = sizeof(arr1) / sizeof(arr1[0]);
   int n2 = sizeof(arr1) / sizeof(arr1[0]);
   printf("%d
",minMaxProduct (arr1, arr2, n1, n2));    return 0; }

Output

If run the above code it will generate the following output −

22

Updated on: 13-Aug-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements