Last Updated: 27 Mar, 2025

Find the maximum element of each row

Easy
Asked in company
Nirmata

Problem statement

You are given a matrix 'M' with 'R' rows and 'C' columns of integers.


Return an array containing the maximum value of each row in 'M'.


For Example :
Let 'R' = 3, 'C' = 4, and 'M' be:
[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12]]
The maximum value of the first row is 4.
The maximum value of the second row is 8.
The maximum value of the third row is 12.
Therefore, the answer is [4 8 12].
Input Format :
The first line contains two integers, 'R' and 'C', representing the number of rows and columns in the matrix 'M'.
The next 'R' lines each contain 'C' integers, representing the elements of the matrix 'M'.
Output Format :
Return an array containing the maximum value of each row in 'M'.
Note :
You don’t need to print anything. Just implement the given function.
Constraints :
1 <= 'R, C' <= 10^3
-10^5 <= 'M[i][j]' <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

Approach:

  • Initialize an empty array to store the maximum values of each row.
  • Iterate through each row of the input matrix.
  • For each row, iterate through its elements and keep track of the maximum value encountered so far.
  • After iterating through all elements in a row, add the maximum value to the result array.
  • Return the result array.

Algorithm:

  • Initialize an empty array 'result'.
  • Iterate using 'i' from 0 to 'R - 1' :
    • Initialize a variable 'max_val' to the first element of the i-th row of 'M'.
    • Iterate using 'j' from 1 to 'C - 1' :
      • If ( M[ i ][ j ] > max_val ) :
        • Set 'max_val' to 'M[ i ][ j ]'.
    • Append 'max_val' to 'result'.
  • Return 'result'.