Maximum Rows Covered by Columns Problem
Description
LeetCode Problem 2397.
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.
A row is considered covered if all the 1's in that row are also part of a column that you have selected. If a row does not have any 1s, it is also considered covered.
More formally, let us consider selected = {c_1, c_2, ...., c_numSelect} as the set of columns selected by you. A row i is covered by selected if:
- For each cell where
matrix[i][j] == 1, the columnjis inselected. - Or, no cell in row
ihas a value of1.
Return the maximum number of rows that can be covered by a set of numSelect columns.
Example 1:

Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
Output: 3
Explanation:
One possible way to cover 3 rows is shown in the diagram above.
We choose s = {0, 2}.
- Row 0 is covered because it has no occurrences of 1.
- Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s.
- Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s.
- Row 3 is covered because matrix[2][2] == 1 and 2 is present in s.
Thus, we can cover three rows.
Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.
Example 2:

Input: matrix = [[1],[0]], numSelect = 1
Output: 2
Explanation:
Selecting the only column will result in both rows being covered since the entire matrix is selected.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 12matrix[i][j]is either0or1.1 <= numSelect <= n
Solution
Approach: Binary Enumeration
Turn each row into a bitmask rows[i], where bit j is set when matrix[i][j] = 1.
Then try every column subset mask out of the 2^n possibilities and skip those that do not have exactly numSelect bits. A row is covered when all its 1s lie inside the chosen columns, that is, when rows[i] & mask == rows[i]. Count the covered rows and keep the best count.
Complexity: O(2n · m) time and O(m) space, where m and n are the numbers of rows and columns.
class Solution:
def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int:
rows = []
for row in matrix:
mask = 0
for j, x in enumerate(row):
if x:
mask |= 1 << j
rows.append(mask)
ans = 0
for mask in range(1 << len(matrix[0])):
if bin(mask).count("1") != numSelect:
continue
t = sum((x & mask) == x for x in rows)
ans = max(ans, t)
return ans