Row with Maximum number of 1's

Given a matrix with sorted rows find the row with maximum number of 1's.

Naive Solution: T: O(m*n)
   In the outer loop select a row. In inner loop cont the number of 1's in that row. update the max count after every iteration. If we found count equal to column number then break. Because the count can be no more that.

import java.util.*;

public class Solution {
 
    public static void main(String[] args) {
        int[][] a = {{0,1,1,1},{0,0,1,1},{1,1,1,1},{0,0,0,0}};
        int m = a.length;
        int n = a[0].length;
        int max = 0;
        int row = -1;
        for(int i=0; i<m; i++){
            int count = n;
            for(int j=0; j<n && a[i][j]==0; j++){
                count--;
            }
            if(count>max){
                max = count;
                row = i;
                if(count == n){
                    break;
                }
            }
        }
        System.out.print(row);
     
       }
}

Output:
2

Efficient Solution:  T: O(m+n)
 Start processing from top right corner of first row
       If there is 1 move left
       If there is 0 move down

Code:
import java.util.*;

public class Solution {
   
    public static void main(String[] args) {
       
         int[][] a = {{0,0,0,1},{0,0,1,1},{0,1,1,1},{1,1,1,1}};
         int row = a.length;
         int col = a[0].length;
         int left = col-1;
         int res = 0;
       
         for(int i=0; i<row; i++){
             for(int j=left; j>=0; j--){
                if(a[i][j] != 1){
                    break;
                }
                 else{
                     res = i;
                     left--;
                 }
            }
         }
       
       System.out.print(res);
   
    }
}

Output:
3





















Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Find Maximum in Binary Tree