Python Program for Maximum and Minimum in a square matrix.
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.
Python3
def MAXMIN(arr, n):
MAX = - 10 * * 9
MIN = 10 * * 9
for i in range (n):
for j in range (n):
if ( MAX < arr[i][j]):
MAX = arr[i][j]
for i in range (n):
for j in range (n):
if ( MIN > arr[i][j]):
MIN = arr[i][j]
print ( "Maximum = " , MAX , " Minimum = " , MIN )
arr = [[ 5 , 9 , 11 ], [ 25 , 0 , 14 ],[ 21 , 6 , 4 ]]
MAXMIN(arr, 3 )
|
Output
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.
Python3
MAX = 100
def MAXMIN(arr, n):
MIN = 10 * * 9
MAX = - 10 * * 9
for i in range (n):
for j in range (n / / 2 + 1 ):
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 ]
print ( "MAXimum =" , MAX , ", MINimum =" , MIN )
arr = [[ 5 , 9 , 11 ],
[ 25 , 0 , 14 ],
[ 21 , 6 , 4 ]]
MAXMIN(arr, 3 )
|
Output:
Maximum = 25, Minimum = 0
Please refer complete article on Maximum and Minimum in a square matrix. for more details!
Last Updated :
21 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...