Find the maximum element of each row

Easy
0/40
1 upvote
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].
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
3 3
1 2 3
4 5 2
7 8 9
Sample Output 1 :
3 5 9
Explanation of sample input 1 :
The input matrix 'M' has 3 rows and 3 columns:
[[1, 2, 3],
 [4, 5, 2],
 [7, 8, 9]]
The maximum value in the first row [1, 2, 3] is 3.
The maximum value in the second row [4, 5, 2] is 5.
The maximum value in the third row [7, 8, 9] is 9.
Thus, the answer is [3 5 9].
Sample Input 2 :
2 4
10 20 5 15
-5 -10 -2 -8
Sample Output 2 :
20 -2
Hint

Iterate through each row of the matrix and find the maximum element in that row.

Approaches (1)
Implementation

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'.
Time Complexity

O(R * C), where 'R' is the number of rows and 'C' is the number of columns in the matrix 'M'.

We iterate through each of the 'R' rows and for each row, we iterate through its 'C' columns to find the maximum. Thus, the overall time complexity is of the order O(R * C).

Space Complexity

O(R), where 'R' is the number of rows in the matrix 'M'.

We create an array 'result' of size 'R' to store the maximum of each row. Thus, the overall space complexity is of the order O(R).

Code Solution
(100% EXP penalty)
Find the maximum element of each row
Full screen
Console