![]() |
VOOZH | about |
Given a m * n binary matrix mat[][] consisting of only 1's and 0's. Each row of the array is sorted in non-decreasing order. Find and return the index of the first row that contains the maximum number of 1's. If no such row exists, return -1.
Examples:
Input: mat[][] = [[ 0 0 1 1 ]
[0 1 1 1 ]
[0 0 1 1 ]
[0 0 0 0 ]]
Output: 1
Explanation: row = 1 has maximum number of 1's, that is 3.Input: mat[][] = [ [ 0 1 1 1 ]
[ 0 0 1 1 ]
[ 1 1 1 1 ]
[ 0 0 0 0 ]]
Output: 2
Explanation: row = 2 has maximum number of 1's, that is 4.
Table of Content
A simple method is to do a row-wise traversal of the matrix, count the number of 1s in each row, and compare the count with the max. Finally, return the index of the row with a maximum of 1's.
2
The idea is to take advantage of the fact that each row is sorted. We use binary search (lower_bound )to find the first occurrence of
1in each row. Once we get this index, the number of 1s in that row is calculated as the total number of columns minus the index of the first1. We keep track of the row with the maximum count of 1s while traversing all rows.
Working of approach:
Traverse each row and use lower_bound (binary search) to find the first occurrence of 1.
Row 2 has the maximum number of 1s, so return index 2.
2
The idea is to use the sorted property of rows to avoid checking all elements.Start from the top-right cell(row = 0, col = n- 1) and store the ans = -1. If the value in the current cell is 1, update ans with the current row and move left. Otherwise, if the current cell is 0, move to the next row:
- If mat[row][col] == 1, update ans = row and move left by col = col - 1.
- Else if mat[row][col] == 0, row = row + 1.
Continue, till we move outside the grid and return ans.
2