LeetCode 2397: Maximum Rows Covered by Columns Solution

Master LeetCode problem 2397 (Maximum Rows Covered by Columns), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2397. Maximum Rows Covered by Columns

Problem Explanation

Explanation:

To solve this problem, we can iterate over all possible combinations of selecting numSelect columns from the given matrix. For each combination, we check how many rows can be covered using those columns. We keep track of the maximum number of rows covered and return that as the result.

  1. Generate all combinations of selecting numSelect columns.
  2. For each combination, check how many rows can be covered.
  3. Return the maximum number of rows covered.

Time Complexity:

  • Generating all combinations: O(2^n)
  • Checking rows covered for each combination: O(m)
  • Total time complexity: O(2^n * m)

Space Complexity:
The space complexity is O(1) as we are not using any additional data structures that grow with the input size.

:

Solution Code

class Solution {
    public int maxRowsCovered(int[][] matrix, int numSelect) {
        int m = matrix.length;
        int n = matrix[0].length;
        int maxCovered = 0;

        for (int comb = 0; comb < (1 << n); comb++) {
            if (Integer.bitCount(comb) != numSelect) continue;
            int rowsCovered = 0;

            for (int row = 0; row < m; row++) {
                boolean covered = true;
                for (int col = 0; col < n; col++) {
                    if ((comb & (1 << col)) > 0 && matrix[row][col] == 1) {
                        covered = true;
                        break;
                    }
                }
                if (covered) rowsCovered++;
            }

            maxCovered = Math.max(maxCovered, rowsCovered);
        }

        return maxCovered;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2397 (Maximum Rows Covered by Columns)?

This page provides optimized solutions for LeetCode problem 2397 (Maximum Rows Covered by Columns) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2397 (Maximum Rows Covered by Columns)?

The time complexity for LeetCode 2397 (Maximum Rows Covered by Columns) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2397 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2397 in Java, C++, or Python.

Back to LeetCode Solutions