Leetcode 2643. Row With Maximum Ones
You are given a rectangular matrix grid
of size m x n
, where each cell contains either 0
or 1
.
Return the row number of the row with the maximum number of 1
s. If there are multiple rows with the same number of 1
s, return the index of the first such row.
You may assume that the matrix grid
has at least one row and one column.
Input: grid = [[0,1,1,0],[0,0,0,0],[0,1,1,1]]
Output: 2
Explanation: The row indexed 2 has 3 ones, which is the maximum.
[1, 1000]
.1
s and the maximum count of 1
s encountered so far.grid
.1
s.1
s compared to the previous maximum count.1
s.public class MaximumOnesRow {
public int rowWithMaxOnes(int[][] grid) {
int maxOnesRowIndex = -1;
int maxOnesCount = -1;
for (int i = 0; i < grid.length; i++) {
int count = 0;
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
count++;
}
}
if (count > maxOnesCount) {
maxOnesCount = count;
maxOnesRowIndex = i;
}
}
return maxOnesRowIndex;
}
public static void main(String[] args) {
MaximumOnesRow solution = new MaximumOnesRow();
int[][] grid1 = {
{0, 1, 1, 0},
{0, 0, 0, 0},
{0, 1, 1, 1}
};
System.out.println(solution.rowWithMaxOnes(grid1)); // Output: 2
int[][] grid2 = {
{0, 1, 1},
{1, 1, 1},
{0, 0, 1}
};
System.out.println(solution.rowWithMaxOnes(grid2)); // Output: 1
}
}
O(m * n)
, where m
is the number of rows and n
is the number of columns. This is because we are iterating through each cell of the matrix exactly once.O(1)
, as we are only using a constant amount of extra space.This approach ensures that we efficiently determine the row with the most 1
s while adhering to the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?