Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, April 21, 2020

Maximum no of 1's row


Problem :



Find out the row which has maximum number of 1 given that all the rows are sorted.




Example :


0 1 1 1
0 0 1 1
1 1 1 1  // this row has maximum 1s
0 0 0 0

Output: 2





Solution :



As we know that it is sorted then we know that there will be 1 at the end of the row which has max 1.

So we will start from the last column and check if it is one then we go ahead and check for CurrentColum-1.

Until we receive 0 or we are at the 0th index.

And in case if it is 0 we just change the row and assign max row id = currentRow.





Code:



 

  public static int fn(int a[][],int n,int m)
  {
   int row = 0;
   int col = m-1;
   int maxRowId = -1;
   while(row<n && col>=0) {
       if(a[row][col] == 1)
       {
           --col;
           maxRowId = row;
       }
       else
       ++row;
   }

0 Comments:

Post a Comment

Stats