Problem · Array

Row with Maximum Ones

Learn this problem
MediumAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

You are given a non-empty rectangular binary matrix matrix. Every row is sorted in nondecreasing order, so all 0 values in a row appear before its 1 values.

Return the zero-based index of the row that contains the maximum number of 1 values. If several rows have the same maximum count, return the smallest such row index. If the entire matrix contains no 1 values, return -1.

Function

rowWithMaxOnes(matrix: int[][]) → int

Examples

Example 1

matrix = [[0,0,0,1],[0,1,1,1],[0,0,1,1]]return = 1

Rows 0, 1, and 2 contain 1, 3, and 2 ones, respectively, so row 1 is returned.

Example 2

matrix = [[0,1,1],[0,1,1],[0,0,1]]return = 0

Rows 0 and 1 both contain two ones. The smaller tied index is 0.

Example 3

matrix = [[0,0],[0,0],[0,0]]return = -1

The matrix contains no ones, so the result is -1.

Constraints

  • 1 <= matrix.length <= 1000
  • 1 <= matrix[i].length <= 1000
  • matrix.length * matrix[i].length <= 1000000
  • Every row has the same length.
  • matrix[i][j] is 0 or 1.
  • Every row is sorted in nondecreasing order.

More Amazon problems

drafts saved locally
public int rowWithMaxOnes(int[][] matrix) {
  // write your code here
}
matrix[[0,0,0,1],[0,1,1,1],[0,0,1,1]]
expected1
checking account