Maximum Rows Covered by Columns - 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 the matrix such that you cover as many rows as possible.
A row is considered covered if:
- All the
1's in that row are in columns that you have selected, OR - The row contains no
1's at all (empty rows are always covered)
For example, if a row is [0, 1, 0, 1, 0] and you select columns {1, 3}, this row is covered because all its 1's are in your selected columns.
Return the maximum number of rows that can be covered by selecting exactly numSelect columns.
Input & Output
example_1.py โ Basic Case
$
Input:
matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
โบ
Output:
3
๐ก Note:
Selecting columns 1 and 2 covers 3 rows: Row 0 (no 1's), Row 2 (1's in cols 1,2), and Row 3 (1 in col 2). Row 1 has 1's in cols 0,2 but we didn't select col 0, so it's not covered.
example_2.py โ All Rows Covered
$
Input:
matrix = [[1],[0],[0]], numSelect = 1
โบ
Output:
3
๐ก Note:
Selecting column 0 covers all 3 rows: Row 0 (1 in selected col 0), Row 1 (no 1's), Row 2 (no 1's). All rows without 1's are automatically covered.
example_3.py โ Optimal Selection
$
Input:
matrix = [[1,0,0,0,0,1,1,0],[1,0,0,0,0,0,1,1],[1,0,0,0,0,0,1,1]], numSelect = 4
โบ
Output:
3
๐ก Note:
We can select columns {0,5,6,7} to cover all 3 rows. Row 0 needs cols 0,5,6. Rows 1,2 need cols 0,6,7. Selecting all four covers everything.
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Floor Plans
Each row represents a floor layout with important areas marked as 1's
2
Budget Constraint
You must install exactly numSelect cameras in different positions (columns)
3
Coverage Rule
A floor is secure only if ALL its important areas are monitored by your cameras
4
Optimization Goal
Find camera placement that secures the maximum number of floors
Key Takeaway
๐ฏ Key Insight: This is a combinatorial optimization problem where we must exhaustively try different combinations to find the optimal solution, but bit manipulation can significantly speed up the coverage checking process.
Time & Space Complexity
Time Complexity
O(C(n, numSelect) * m * n)
C(n, numSelect) combinations, each taking O(m * n) to evaluate all rows and columns
โ Linear Growth
Space Complexity
O(numSelect)
Space to store current combination of selected columns
โก Linearithmic Space
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค m, n โค 12
- matrix[i][j] is either 0 or 1
- 1 โค numSelect โค n
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code