Problem Description
Given an m x n binary matrix and an integer numSelect, the goal is to select exactly numSelect distinct columns to maximize the number of covered rows. A row is considered covered if every cell containing a 1 has its corresponding column selected. Additionally, rows with no 1’s are automatically covered.
Key Insights
- Use bitmasks to represent rows and selected columns since n (the number of columns) is at most 12.
- Precompute a bitmask for each row where each bit represents if that column has a 1.
- Enumerate over all possible combinations of columns (bitmask with exactly numSelect bits set).
- For each combination, check each row: a row is covered if the row’s bitmask is a subset of the selected columns’ bitmask.
- Due to small constraints (m, n ≤ 12), this brute-force enumeration approach is efficient.
Space and Time Complexity
Time Complexity: O(Combination(n, numSelect) * m)
Space Complexity: O(m) (for storing the bitmask of each row)
Solution
We precompute a bitmask for each row where each bit is set if the corresponding column has a 1. Then, we generate every possible subset of columns (as a bitmask) that contains exactly numSelect bits. For each subset, we check how many rows are covered by verifying that for each row, the row’s bitmask is a subset of the selected columns bitmask (i.e. bitwise AND equals the row’s bitmask). The maximum number of covered rows across all subsets is our answer.