C語言中第一個陣列的最大值和第二個陣列的最小值的乘積


給定兩個陣列 arr1[] 和 arr2[],它們的大小分別為 n1 和 n2,我們需要找到第一個陣列 arr1[] 中的最大元素和第二個陣列 arr2[] 中的最小元素的乘積。

例如,arr1[] = {5, 1, 6, 8, 9} 和 arr2[] = {2, 9, 8, 5, 3},那麼 arr1 中的最大元素是 9,arr2 中的最小元素是 2,所以兩者的乘積是 9*2 = 18,同樣,我們需要編寫一個程式來解決給定的問題。

輸入

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

輸出

18

解釋

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

輸入

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

輸出

22

解釋

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

下面使用的解決問題的方法如下

  • 我們將把兩個陣列 arr1 和 arr2 作為輸入。

  • 我們將把兩個陣列都按升序排序。

  • 我們將 arr1 的最後一個元素(最大元素)和 arr2 的第一個元素(最小元素)相乘。

  • 返回乘積。

演算法

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

示例

即時演示

#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; }

輸出

如果執行以上程式碼,它將生成以下輸出:

22

更新於: 2020-08-13

237 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告