LeetCode in Kotlin

2397. Maximum Rows Covered by Columns

Medium

You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix.

Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:

You need to choose numSelect columns such that the number of rows that are covered is maximized.

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}.

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.

Therefore, we return 2.

Constraints:

Solution

class Solution {
    private var ans = 0
    fun maximumRows(matrix: Array<IntArray>, numSelect: Int): Int {
        dfs(matrix, /*colIndex=*/0, numSelect, /*mask=*/0)
        return ans
    }

    private fun dfs(matrix: Array<IntArray>, colIndex: Int, leftColsCount: Int, mask: Int) {
        if (leftColsCount == 0) {
            ans = Math.max(ans, getAllZerosRowCount(matrix, mask))
            return
        }
        if (colIndex == matrix[0].size) {
            return
        }
        // choose this column
        dfs(matrix, colIndex + 1, leftColsCount - 1, mask or (1 shl colIndex))
        // not choose this column
        dfs(matrix, colIndex + 1, leftColsCount, mask)
    }

    private fun getAllZerosRowCount(matrix: Array<IntArray>, mask: Int): Int {
        var count = 0
        for (row in matrix) {
            var isAllZeros = true
            for (i in row.indices) {
                if (row[i] == 1 && mask shr i and 1 == 0) {
                    isAllZeros = false
                    break
                }
            }
            if (isAllZeros) {
                ++count
            }
        }
        return count
    }
}