Given a m x n
binary matrix mat
, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.
In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.
Return an array containing the index of the row, and the number of ones in it.
LeetCode Problem - 2643
class Solution {
// Method to find the row with the maximum number of ones and the count of ones in that row
public int[] rowAndMaximumOnes(int[][] mat) {
int rowNum = 0; // To store the row number with the maximum ones
int count = 0; // To store the maximum count of ones
// Iterate through each row of the matrix
for(int i = 0; i < mat.length; i++){
int tempCount = 0; // Temporary count of ones for the current row
// Iterate through each element in the row
for(int j = 0; j < mat[0].length; j++){
// Increment the count if the element is 1
if(mat[i][j] == 1){
tempCount++;
}
}
// Update the maximum count and row number if the current row has more ones
if(tempCount > count){
count = tempCount;
rowNum = i;
}
}
// Create an array to store the result
int[] ans = new int[2];
ans[0] = rowNum; // The row number with the maximum ones
ans[1] = count; // The count of ones in that row
// Return the result
return ans;
}
}