1788. Column Picks Cover

Medium3.5 points estimatedEnumerationBitmaskMatrix

A kitchen has several orders, one per row of matrix, and a set of ingredient stations, one per column. matrix[i][j] is 1 when order i needs station j and 0 otherwise. You may switch on exactly k stations. An order is served when every station it needs is switched on; an order that needs no station at all is always served.

Each order i is worth weights[i]. Return the largest total worth of served orders, as a long. Encode every row as a bitmask of the stations it needs, enumerate every station mask with exactly k bits set, and add the weights of the rows whose mask is a subset of the chosen one. Only the total is returned, so different station sets with the same total are equivalent. Time is O(C(cols, k) * rows) after O(rows * cols) preprocessing, with O(rows) extra space.

Example 1

Input:
matrix = [[1,0,0],[1,1,0],[0,0,0],[0,1,1]]weights = [5,3,2,7]k = 2
Output:
10
Explanation:

Switching on stations 0 and 1 serves orders 0, 1 and 2, giving the best total 10.

Example 2

Input:
matrix = [[1,1],[0,1]], weights = [4,9], k = 1
Output:
9
Explanation:

With one station only the order needing station 1 alone can be served, so the best total is 9.

Example 3

Input:
matrix = [[0,0],[0,0]], weights = [6,8], k = 2
Output:
14
Explanation:

Both orders need nothing, so they are always served and the total is 14.

Constraints

1 ≤ rows, cols ≤ 12; matrix[i][j] is 0 or 1

weights.length == rows; 1 ≤ weights[i] ≤ 106; 1 ≤ k ≤ cols

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(C(cols, k) * rows)
Space
O(rows)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…