Row with Maximum 1's
EasyCount 1s per row with lower bound
Each row is sorted, so find where its 1s begin; the row whose 1s start earliest has the most.
The idea
Each row is sorted (0s then 1s), so the number of 1s is cols minus the lower bound of 1. Take the row with the most.
0
0
1
0
1
1
0
0
0
Step 1 of 5. Brute force: count the 1s in every row, keep the biggest.
1/5
Brute force
timeO(m·n)spaceO(1)
Count each row.
1for (let r = 0; r < R; r++) {2 const ones = mat[r].reduce((s, v) => s + v, 0);3 if (ones > best) { best = ones; bestRow = r; }4}Input
- grid
- 3 × 3
Memory
- cells marked
- 0
Output
- best row
- —
- ones
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- matrix = [[0,0,1],[0,1,1],[0,0,0]]
- Output:
- 1
- Explanation:
- Row 1 has the most 1s.
Example 2
- Input:
- matrix = [[1,1],[0,1]]
- Output:
- 0
- Explanation:
- Row 0 is all ones.
Example 3
- Input:
- matrix = [[0,0],[0,0]]
- Output:
- 0
- Explanation:
- No ones anywhere → row 0.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.