Row With Maximum Ones

We need to go through each row in the matrix, count the number of ones, and keep track of the row that has the most ones. If two rows have the same number of ones, we prefer the row with a smaller index.

We can achieve this using a simple for loop to iterate through the rows of the matrix. In the loop, we use the built-in sum function to count the number of ones in each row (since ones are represented by the number 1 and zeros by the number 0, summing the row gives us the count of ones).

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
        max_ones = -1  # Initialize maximum ones count
        idx = -1  # Initialize index of row with maximum ones

        for i in range(len(mat)):  # Go through each row
            current_ones = sum(mat[i])  # Count ones in the current row

            # If this row has more ones than the maximum found so far,
            # or if it has the same number of ones but a smaller index, update max_ones and idx.
            if current_ones > max_ones or (current_ones == max_ones and i < idx):
                max_ones = current_ones
                idx = i

        # After going through all rows, return the index of the row with the most ones and the count of ones.
        return [idx, max_ones]

This solution works for all inputs within the problem’s constraints, and its time complexity is O(m*n), where m is the number of rows and n is the number of columns in the matrix.