1787. Blackout Strips

Medium3.5 points estimatedEnumerationBitmaskMatrixGreedySorting

A warehouse floor is laid out as a grid of storage cells, and each cell carries a profit value that may be negative because of upkeep costs. For a blackout drill you must shut down exactly dropRows whole rows and exactly dropCols whole columns of grid. The cells lying in neither a shut row nor a shut column keep running, and their values add up to your score.

Return the largest score you can reach as a long; if no cell remains the score is 0. Once the rows to keep are fixed the columns are independent: total each column over the kept rows and shut the dropCols columns with the smallest totals. So try every set of rows as a bitmask. Only the score is returned, so ties between equal columns never matter. Intended cost is O(C(rows, dropRows) * (rows * cols + cols log cols)) time and O(cols) extra space.

Example 1

Input:
grid = [[1,-2,3],[4,5,-6],[-7,8,9]]dropRows = 1dropCols = 1
Output:
18
Explanation:

Shutting one row and one column leaves a 2 by 2 block; the best block sums to 18.

Example 2

Input:
grid = [[5,-1],[-2,7]], dropRows = 1, dropCols = 0
Output:
5
Explanation:

Shut the row with the smaller total, leaving a single row whose cells add up to 5.

Example 3

Input:
grid = [[-3,-4],[-5,-6]], dropRows = 2, dropCols = 2
Output:
0
Explanation:

Every row and column is shut, so nothing remains and the score is 0.

Constraints

1 ≤ rows ≤ 12; 1 ≤ cols ≤ 80; rows * cols ≤ 1000

0 ≤ dropRows ≤ rows; 0 ≤ dropCols ≤ cols

-104 ≤ grid[i][j] ≤ 104

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(rows, dropRows) * (rows * cols + cols log cols))
Space
O(cols)

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…