Php Program to Find maximum element of each row in a matrix
Last Updated :
20 Feb, 2023
Given a matrix, the task is to find the maximum element of each row.
Examples:
Input : [1, 2, 3]
[1, 4, 9]
[76, 34, 21]
Output :
3
9
76
Input : [1, 2, 3, 21]
[12, 1, 65, 9]
[1, 56, 34, 2]
Output :
21
65
56
Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finally, print the element.
Below is the implementation :
PHP
<?php
$N = 4;
function printArray( $result , $no_of_rows )
{
for ( $i = 0; $i < $no_of_rows ; $i ++)
{
echo $result [ $i ]."
";
}
}
function maxelement( $no_of_rows , $arr )
{
global $N ;
$i = 0;
$max = 0;
$result = array_fill (0, $no_of_rows ,0);
while ( $i < $no_of_rows )
{
for ( $j = 0; $j < $N ; $j ++)
{
if ( $arr [ $i ][ $j ] > $max )
{
$max = $arr [ $i ][ $j ];
}
}
$result [ $i ] = $max ;
$max = 0;
$i ++;
}
printArray( $result , $no_of_rows );
}
$arr = array ( array (3, 4, 1, 8),
array (1, 4, 9, 11),
array (76, 34, 21, 1),
array (2, 1, 4, 5));
maxelement(4, $arr );
?>
|
Output :
8
11
76
5
Time Complexity: O(N * M) where N is the number of rows and M is the number of columns in the given matrix.
Space Complexity: O(N) where N is the number of rows in the given matrix.
Please refer complete article on Find maximum element of each row in a matrix for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...