Given a 2D binary matrix matrix of size n x m where each row is sorted in non-decreasing order (all 0s appear before all 1s in every row), find the 0-based index of the row that contains the maximum number of 1s.
If multiple rows have the same maximum number of 1s, return the row with the smallest index. If no row contains a 1, return -1.
Function Signature
def row_with_max_ones(matrix: list[list[int]]) -> int:
Rules
-
Rows are indexed from 0.
-
When several rows tie for the maximum count of 1s, return the smallest of their indices.
-
Return
-1
when no cell of the matrix is a 1.
Constraints
-
1 <= n, m <= 1000
-
matrix[i][j]
is either
0
or
1
-
Each row of
matrix
is sorted in non-decreasing order
Examples
Input: matrix = [[0,1,1,1],[0,0,1,1],[1,1,1,1],[0,0,0,0]]
Output: 2
The rows hold three, two, four and zero 1s. Row 2 is the only row with four.
Input: matrix = [[0,0],[0,0]]
Output: -1
No row contains a 1, so the answer is -1.
Input: matrix = [[0,0,1],[0,1,1],[0,1,1]]
Output: 1
Rows 1 and 2 both hold two 1s, the maximum. The tie goes to the smaller index, 1.