Given a m x n
matrix, find the maximum element of each row in the matrix.
Matrix:
[[12, 43],
[234, 54],
[642, 687],
[23, 99]]
Result:
[43, 234, 687, 99]
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:
O(m*n)
O(1)
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));}}