How to find the row with maximum number of 1’s in sorted rows binary digits matrix with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
 
int FindRowWithMaximumOnes(std::vector<std::vector<int>> const &matrix) {
    if (matrix.size() == 0) {
        return -1;
    }
  
    int rows = matrix.size();
    int cols = matrix[0].size();
 
    int row_index = -1;
  
    int i = 0, j = cols - 1;
  
    while (i <= rows - 1 && j >= 0) {
        if (matrix[i][j]) {
            j--, row_index = i;   
        }
        else {              
            i++; // next row
        }
    }
  
    return row_index;
}
  
int main()
{
    std::vector<std::vector<int>> matrix =
    {
        { 0, 0, 0, 0, 1, 1 },
        { 0, 0, 1, 1, 1, 1 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 1, 1, 1, 1, 1 },
        { 0, 0, 0, 1, 1, 1 }
    };
  
 
    std::cout << "Row index = " << FindRowWithMaximumOnes(matrix);
}
 
 
 
/*
run:
 
Row index = 3
 
*/

 



answered Sep 24, 2022 by avibootz
edited Sep 24, 2022 by avibootz
...