Row With Maximum Ones - Problem

Given an m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.

In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.

Return an array containing the index of the row, and the number of ones in it.

Input & Output

Example 1 — Basic Case
$ Input: mat = [[0,1,1,1],[0,0,1,1],[0,0,0,1]]
Output: [0,3]
💡 Note: Row 0 has 3 ones, Row 1 has 2 ones, Row 2 has 1 one. Maximum is 3 in row 0.
Example 2 — Tie Breaking
$ Input: mat = [[0,0],[1,1],[0,0]]
Output: [1,2]
💡 Note: Only Row 1 has ones (2 ones), so return [1,2].
Example 3 — Multiple Ties
$ Input: mat = [[0,1],[1,0],[0,1]]
Output: [0,1]
💡 Note: Rows 0, 1, and 2 all have 1 one each. Return smallest row index [0,1].

Constraints

  • 1 ≤ m, n ≤ 100
  • mat[i][j] is either 0 or 1

Visualization

Tap to expand
Row With Maximum Ones INPUT Binary Matrix (3x4) Row 0: 0 1 1 1 =3 Row 1: 0 0 1 1 =2 Row 2: 0 0 0 1 =1 Input Values: mat = [[0,1,1,1], [0,0,1,1],[0,0,0,1]] = 1 (one) = 0 (zero) ALGORITHM STEPS 1 Initialize maxOnes=0, rowIdx=0 2 Count Ones per Row Row 0: count=3 (max!) 3 Early Exit Check If count==cols, stop! 4 Return Result [rowIdx, maxOnes] Execution Trace: Row 0: ones=3, max=3 3 == 4? No, continue Row 1: ones=2 < 3, skip Row 2: ones=1 < 3, skip FINAL RESULT Winner: Row 0 Row 0: 0 1 1 1 Maximum ones count: 3 Found at row index: 0 OUTPUT [0, 3] Interpretation: Index 0 = Row number Value 3 = Count of ones OK - Verified! Key Insight: Early Exit Optimization If a row has ALL ones (count == number of columns), we can immediately return that row. No subsequent row can have more ones, and earlier rows with same count would have been selected already. TutorialsPoint - Row With Maximum Ones | Optimized - Early Exit on All Ones
Asked in
Microsoft 15 Amazon 12
24.0K Views
Medium Frequency
~8 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen