Now, i am going to give your a better approach. Please see the approach, the Time Complexity: O(mLogn). Each row is sorted, we can use Binary Search to count of 1s in each row. We find the index of first instance of 1 in each row. And count of 1s will be equal to total number of columns minus the index of first 1.
See the code for find the row with maximum number 1s:-
//Time Complexity: O(mLogn)
//Where m is number of rows and n is number of columns
private static int getRowNumberWithMax1s(int[][] arr, int R, int C) {
int max_row_index = 0, max = -1;
// Traverse for each row and count number of 1s to find the index of first 1
int i, index;
for (i = 0; i < R; i++) {
index = first(arr[i], 0, C - 1);
if (index != -1 && C - index > max) {
max = C - index;
max_row_index = i;
}
}
return max_row_index;
}
private static int first(int arr[], int low, int high) {
if (high >= low) {
// Get middle index
int mid = low + (high - low) / 2;
// Check if an element at middle index is first 1
if ((mid == 0 || (arr[mid - 1] == 0)) && arr[mid] == 1)
return mid;
// If an element is 0, recur for right side
else if (arr[mid] == 0)
return first(arr, (mid + 1), high);
// If an element is not first 1, recur for left side
else
return first(arr, low, (mid - 1));
}
return -1;
}
Output:-
2 row has maximum 1s