Given a square matrix of order n*n, find the maximum and minimum from the matrix given.
Examples:
Input : arr[][] = {5, 4, 9, 2, 0, 6, 3, 1, 8}; Output : Maximum = 9, Minimum = 0 Input : arr[][] = {-5, 3, 2, 4}; Output : Maximum = 4, Minimum = -5
Naive Method :
We find maximum and minimum of matrix separately using linear search. Number of comparison needed is n2 for finding minimum and n2 for finding the maximum element. The total comparison is equal to 2n2.
C++
// C++ program for finding maximum and minimum in // a matrix. #include<bits/stdc++.h> using namespace std; // Finds maximum and minimum in arr[0..n-1][0..n-1] // using pair wise comparisons void maxMin( int arr[3][3], int n) { int min = INT_MAX; int max = INT_MIN; // for finding the max element in given array for ( int i = 0; i<n; i++){ for ( int j = 0; j<n; j++){ if (max < arr[i][j]) max = arr[i][j]; } } // for finding the min element in given array for ( int i = 0; i<n; i++){ for ( int j = 0; j<n; j++){ if (min > arr[i][j]) min = arr[i][j]; } } cout << "Maximum = " << max << ", Minimum = " << min; } // Driver Program to test above function int main(){ int arr[3][3] = {{5, 9, 11} , {25, 0, 14} , {21, 6, 4}}; maxMin(arr, 3); return 0; } // THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999) |
Maximum = 25, Minimum = 0
Pair Comparison (Efficient method):
Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix, compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix. We can see that for two elements we need 3 compare so for traversing whole of the matrix we need total of 3/2 n2 comparisons.
Note : This is extended form of method 3 of Maximum Minimum of Array.
C++
// C++ program for finding maximum and minimum in // a matrix. #include<bits/stdc++.h> using namespace std; #define MAX 100 // Finds maximum and minimum in arr[0..n-1][0..n-1] // using pair wise comparisons void maxMin( int arr[][MAX], int n) { int min = INT_MAX; int max = INT_MIN; // Traverses rows one by one for ( int i = 0; i < n; i++) { for ( int j = 0; j <= n/2; j++) { // Compare elements from beginning // and end of current row if (arr[i][j] > arr[i][n-j-1]) { if (min > arr[i][n-j-1]) min = arr[i][n-j-1]; if (max< arr[i][j]) max = arr[i][j]; } else { if (min > arr[i][j]) min = arr[i][j]; if (max< arr[i][n-j-1]) max = arr[i][n-j-1]; } } } cout << "Maximum = " << max; << ", Minimum = " << min; } /* Driver program to test above function */ int main() { int arr[MAX][MAX] = {5, 9, 11, 25, 0, 14, 21, 6, 4}; maxMin(arr, 3); return 0; } |
Output:
Maximum = 25, Minimum = 0
Time Complexity: O(n^2)
Auxiliary Space: O(1) since no extra space has been taken.
Please refer complete article on Maximum and Minimum in a square matrix. for more details!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!