Find the row with maximum number of 1s using C++


In this problem, we are given a binary matrix where elements of each row are sorted. Our task is to find the row with maximum number of 1s.

Let’s take an example to understand the problem,

Input

mat[][] = {{ 0 1 1 1}
   {1 1 1 1}
   {0 0 0 1}
   {0 0 1 1}}

Output

1

Explanation

The count of 1’s in each row of the matrix :
Row 0 : 3
Row 1 : 4
Row 2 : 1
Row 3 : 2

Solution Approach

A simple solution to the problem is by finding the row with the smallest index of the first 1.

One approach is using row wise traversal to find the first 1’s index which will return the maximum count of 1 in the row. And then we will return the row with maximum 1 count.

Another approach is using binary search to find the occurrence of the first 1 in each row. Then we will return the value with maximum 1.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
#define R 4
#define C 4
int findFirst1BinSearch(bool arr[], int low, int high){
   if(high >= low){
      int mid = low + (high - low)/2;
      if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
         return mid;
      else if (arr[mid] == 0)
         return findFirst1BinSearch(arr, (mid + 1), high);
      else
         return findFirst1BinSearch(arr, low, (mid -1));
   }
   return -1;
}
int findMaxOneRow(bool mat[R][C]){
   int max1RowIndex = 0, max = -1;
   for (int i = 0; i < R; i++){
      int first1Index = findFirst1BinSearch(mat[i], 0, C-1);
      if (first1Index != -1 && C-first1Index > max){
         max = C - first1Index;
         max1RowIndex = i;
      }
   }
   return max1RowIndex;
}
int main(){
   bool mat[R][C] = { {0, 1, 1, 1},
   {1, 1, 1, 1},
   {0, 0, 1, 1},
   {0, 0, 0, 1}};
   cout<<"The row with maximum number of 1's in the matrix is "<<findMaxOneRow(mat);
   return 0;
}

Output

The row with maximum number of 1's in the matrix is 1

Updated on: 14-Feb-2022

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements