


If two rows have the same number of 1’s, return the row with a lower index.
If no row exists where at-least one '1' is present, return -1.
Input: ‘N’ = 3, 'M' = 3
'ARR' =
[ [ 1, 1, 1 ],
[ 0, 0, 1 ],
[ 0, 0, 0 ] ]
Output: 0
Explanation: The 0th row of the given matrix has the maximum number of ones.
The first line contains two integers, ‘N’ and ‘M’, representing the number of rows and columns of the 2D matrix.
Each of the next N lines contains M space-separated integers representing the elements of the matrix ARR.
Return the row index, which contains the maximum number of 1’s.
You do not need to print anything; It has already been taken care of. Just implement the given function.
Our intuition is to traverse the given matrix row by row, and keep on counting the number of ‘1’s in each row and compare the count with max. And finally, return the index of the row with the maximum ‘1’s. This is a brute force kind of approach.
Just remember one thing while considering two rows have the same number of 1’s then we need to return the row with a lower index.
In the previous approach, we were iterating through all the elements of the matrix. Do we really need to do that? Think of how we can search for a point where the 1’s starts to appear since all the rows are sorted as given in the question.
Steps to follow towards a better approach :
In the previous approach, we were searching in each of the given matrix. Can you think of a case in which we can really skip a row in order to make our approach more optimized?
Steps are as follows :