각각 n1 및 n2 크기의 두 배열 arr1[] 및 arr2[]가 주어지면 첫 번째 배열 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