Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which row has the most 1s in a 0-1 matrix with all 1s "on the left"?

Problem

Each row of an n x n matrix consists of 1's and 0's such that in any row, all 1's come before any 0's. Find row containing most no of 1's in O(n).

Example

1 1 1 1 1 0  <- Contains maximum number of 1s, return index 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 1 0 0 0 0 

I found this question in my algorithms book. The best I could do took O(n logn) time. How to do this in O(n)?

like image 798
jaya Avatar asked Mar 22 '11 08:03

jaya


People also ask

What does a row of all zeros in a matrix mean?

Row-Echelon Form If there is a row of all zeros, then it is at the bottom of the matrix. The first non-zero element of any row is a one. That element is called the leading one. The leading one of any row is to the right of the leading one of the previous row.

Is 1 a row matrix?

1. Row matrix: A matrix having a single row.

Which one is row in Matrix?

In mathematics, a row matrix is a type of matrix that has a single row. But the number of columns could be more than one. Therefore, if the matrix is in the order of 1 x n, then it is a row matrix. The elements are arranged in an order such that they represent a single row in the matrix.


1 Answers

Start at 1,1.

If the cell contains 1, you're on the longest row so far; write it down and go right. If the cell contains 0, go down. If the cell is out of bounds, you're done.

like image 55
Thom Smith Avatar answered Sep 22 '22 20:09

Thom Smith