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

2 Answers

0 votes
public class MyClass {
    private static int FindRowWithMaximumOnes(int[][] matrix) {
        if (matrix.length == 0) {
            return -1;
        }
     
        int rows = matrix.length;
        int cols = matrix[0].length;
        int row_index = -1;
        int max_count = 0 ;
     
        for (int i = 0; i < rows; i++) {
            int count = 0 ;
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 1) {
                    count++ ;
                }
            }
            if (count > max_count) {
                max_count = count;
                row_index = i;
            }
        }

        return row_index;
    }
    public static void main(String args[]) {
        int[][] matrix = { { 0, 0, 0, 0, 1, 1 },
                           { 0, 0, 0, 1, 1, 1 },
                           { 0, 0, 0, 0, 0, 1 },
                           { 0, 1, 1, 1, 0, 1 }, 
                           { 0, 0, 0, 1, 1, 1 } };            
 
        System.out.print("Row index = " + FindRowWithMaximumOnes(matrix));
    }
}
 
 
 
 
 
/*
run:
 
Row index = 3
 
*/

 

 



answered Sep 24, 2022 by avibootz
edited Nov 26, 2022 by avibootz
0 votes
public class MyClass {
    private static int FindRowWithMaximumOnes(int[][] matrix) {
        if (matrix.length == 0) {
            return -1;
        }

        int rows = matrix.length;
        int cols = matrix[0].length;
  
        int row_index = -1;
  
        int i = 0;
        int j = cols - 1;
  
        while (i <= rows - 1 && j >= 0) {
            if (matrix[i][j] != 0) {
                j--;
                row_index = i;
            }
            else {
                i++; // next row
            }
        }
  
        return row_index;
    }

    public static void main(String args[]) {
        int[][] matrix = { { 0, 0, 0, 0, 1, 1 },
                           { 0, 0, 0, 1, 1, 1 },
                           { 0, 0, 0, 0, 0, 1 },
                           { 0, 1, 1, 1, 0, 1 }, 
                           { 0, 0, 0, 1, 1, 1 } };            
  
        System.out.print("Row index = " + FindRowWithMaximumOnes(matrix));
    }
}
  
  
  
  
  
/*
run:
  
Row index = 3
  
*/

 



answered Nov 26, 2022 by avibootz
...