Row With Maximum Ones — LeetCode 2643 Python Solution
- Problem
- #2643
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a 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.
Example
- Input
- mat = [[0,1],[1,0]]
- Output
- [0,1]
- Explanation
- Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1].
Python solution
class Solution:
def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
ans = [0, 0]
for i, row in enumerate(mat):
cnt = sum(row)
if ans[1] < cnt:
ans = [i, cnt]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the number of rows and columns in the matrix, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2643. Row With Maximum Ones is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2643. Row With Maximum Ones?
- LeetCode 2643. Row With Maximum Ones is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2643. Row With Maximum Ones?
- The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns in the matrix, respectively.
- What is the space complexity of LeetCode 2643. Row With Maximum Ones?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2643. Row With Maximum Ones cover?
- LeetCode 2643. Row With Maximum Ones is tagged Array and Matrix on LeetCode.