Maximum Rows Covered by Columns — LeetCode 2397 Python Solution
- Problem
- #2397
- Pattern
- Backtracking
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an m x n binary matrix matrix and an integer numSelect. Your goal is to select exactly numSelect distinct columns from matrix such that you cover as many rows as possible.
Python solution
class Solution:
def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int:
rows = []
for row in matrix:
mask = reduce(or_, (1 << j for j, x in enumerate(row) if x), 0)
rows.append(mask)
ans = 0
for mask in range(1 << len(matrix[0])):
if mask.bit_count() != numSelect:
continue
t = sum((x & mask) == x for x in rows)
ans = max(ans, t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(2^n \times m) |
| Space | O(m) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2397. Maximum Rows Covered by Columns is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2397. Maximum Rows Covered by Columns?
- LeetCode 2397. Maximum Rows Covered by Columns is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2397. Maximum Rows Covered by Columns?
- The Python solution on this page runs in O(2^n \times m).
- What is the space complexity of LeetCode 2397. Maximum Rows Covered by Columns?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 2397. Maximum Rows Covered by Columns cover?
- LeetCode 2397. Maximum Rows Covered by Columns is tagged Bit Manipulation, Array, Backtracking, Enumeration and Matrix on LeetCode.