Java Program to Find the Maximum Element in a Matrix
Last Updated :
28 Jul, 2022
Given a multi-dimensional 2D matrix of n rows and m column order N × M. The task is to find the maximum element in the given matrix.
Illustration:
Input : mat[][] = { {1,3,4,19}, {11,10,12,1}, {7,9,0,4,99} }
Output : 99
Methods:
- Iterative method (naive approach)
- Using the principle of recursion (Bit more optimal approach)
Method 1: Iterative method
The approach is simple to iterate every element of the matrix one by one and store the maximum of two elements in the max variable as used below in the program and returns the max variable that contains the maximum element of the matrix.
Example
Java
import java.io.*;
class GFG {
static int max( int mat[][])
{
int max = 0 ;
for ( int i = 0 ; i < mat.length; ++i) {
for ( int j = 0 ; j < mat[ 0 ].length; ++j) {
max = Math.max(mat[i][j], max);
}
}
return max;
}
public static void main(String[] args)
{
int mat[][] = { { 1 , 3 , 4 , 19 },
{ 11 , 10 , 12 , 1 },
{ 7 , 9 , 0 , 99 } };
int max_element = max(mat);
System.out.println(max_element);
}
}
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2: Using the principle of recursion
Procedure:
- Recursively call every element of the matrix to the last element of the matrix.
- Return the max of the current element to the next recursive call element.
Example
Java
import java.io.*;
class GFG {
static int max( int mat[][], int i, int j)
{
if (j == mat[ 0 ].length && i < mat.length) {
j = 0 ;
++i;
}
if (i == mat.length) {
return 0 ;
}
return Math.max(mat[i][j], max(mat, i, j + 1 ));
}
public static void main(String[] args)
{
int mat[][] = { { 1 , 3 , 4 , 19 },
{ 11 , 10 , 12 , 1 },
{ 7 , 9 , 0 , 99 } };
int max_element = max(mat, 0 , 0 );
System.out.println(max_element);
}
}
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...