How to find the maximum element of each row in a matrix

Problem overview

Given a m x n matrix, find the maximum element of each row in the matrix.

Example:

Matrix:

[[12, 43],
[234, 54],
[642, 687],
[23, 99]]

Result:

[43, 234, 687, 99]

Algorithm

Every row in a matrix is an array. Hence, we need to find the maximum element of an array. We use the algorithm described here to get the maximum element from an array.

The steps of the algorithm are as follows:

  • For every row in the matrix, perform the following steps:
    • Initially, the first element will be set as the max, and then the row will be traversed.
    • Each element will be compared with the max, and if the current element is greater than the max, the max will be set to the current element.
    • Finally, the max for the row is returned.
  • Collect all the maximums from the previous step to an array.
    • Time Complexity: O(m*n)
    • Space Complexity: O(1)

Code

import java.util.Arrays;
public class Main {
private static int maxElement(int[] row){
int max = row[0];
for (int i : row) max = Math.max(max, i);
return max;
}
private static int[] maxElementRow(int[][] matrix) {
int[] rowMaxElements = new int[matrix.length];
int i = 0;
for(int[] row: matrix) {
rowMaxElements[i] = maxElement(row);
i++;
}
return rowMaxElements;
}
public static void main(String[] args) {
int[][] matrix = { {12, 43},
{234, 54},
{642, 687},
{23, 99}
};
int[] maxElements = maxElementRow(matrix);
System.out.println("Maximum elements in each row are as follows: ");
System.out.println(Arrays.toString(maxElements));
}
}

Free Resources