#2397
Maximum Rows Covered by Columns
MediumArrayBacktrackingBit ManipulationMatrixEnumerationBit ManipulationCombinatorial Enumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n^2) | O(n * 2^n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n * 2^n)Space O(1)
The optimal solution leverages bit manipulation to efficiently represent and check combinations of columns. This reduces the complexity significantly by avoiding the need to generate all combinations explicitly.
⚙️
Algorithm
3 steps- 1Step 1: Use bit masking to represent selected columns.
- 2Step 2: For each possible combination of columns (from 0 to 2^n - 1), check if it covers the maximum rows.
- 3Step 3: Count the number of rows covered for each combination and keep track of the maximum.
solution.py11 lines
1def maxRowsCovered(matrix, numSelect):
2 m, n = len(matrix), len(matrix[0])
3 max_covered = 0
4 for mask in range(1 << n):
5 if bin(mask).count('1') == numSelect:
6 covered = 0
7 for row in matrix:
8 if all(row[j] == 0 for j in range(n) if (mask & (1 << j)) == 0) or all(row[j] == 1 for j in range(n) if (mask & (1 << j)) != 0):
9 covered += 1
10 max_covered = max(max_covered, covered)
11 return max_coveredℹ
Complexity note: The complexity comes from iterating through all possible combinations of columns (2^n) and checking each row (n) for coverage. This is more efficient than the brute force approach as it avoids generating combinations explicitly.
- 1Using bit manipulation can significantly reduce the complexity of the problem.
- 2Understanding how to represent combinations efficiently is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.