จากสองอาร์เรย์ 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\n",minMaxProduct (arr1, arr2, n1, n2));
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
22