You are given a 2D matrix grid of size n x n. Initially, all cells of the grid are colored white. In one operation, you can select any cell of indices (i, j), and color black all the cells of the jth column starting from the top row down to the ith row.
The grid score is the sum of all grid[i][j] such that cell (i, j) is white and it has a horizontally adjacent black cell.
Return the maximum score that can be achieved after some number of operations.
In the first operation, we color all cells in column 1 down to row 3, and in the second operation, we color all cells in column 4 down to the last row. The score of the resulting grid is grid[3][0] + grid[1][2] + grid[3][3] which is equal to 11.
We perform operations on 1, 2, and 3 down to rows 1, 4, and 0, respectively. The score of the resulting grid is grid[0][0] + grid[1][0] + grid[2][1] + grid[4][1] + grid[1][3] + grid[2][3] + grid[3][3] + grid[4][3] + grid[0][4] which is equal to 94.
Constraints:
1 <= n == grid.length <= 100
n == grid[i].length
0 <= grid[i][j] <= 109
Solutions
Solution 1: Dynamic Programming + Prefix Sum
Thinking
Each column is painted black from the top for some height; a white cell scores only if a neighbor column is black there. \(n\le 100\), so enumerating height tuples is \((n+1)^n\). Column \(j\)'s score depends only on its height and its two neighbors, which suggests a column DP.
\(f[h_1][h_2]\) is the best score with current height \(h_1\) and previous height \(h_2\). When enumerating the next height, \(\max(h_2,h_p)\) makes the addend piecewise, so prefix/suffix maxima over \(h_2\) drop a column from \(O(n^3)\) to \(O(n^2)\). Column prefix sums precompute white-range totals.
For each column \(j\), let \(k[j] \in \{0, 1, \ldots, n\}\) be the number of cells colored black from the top. A white cell \((i, j)\) scores if and only if at least one horizontally adjacent cell is black, and it is counted only once. The contribution of column \(j\) is therefore:
where \(s[j][h]\) is the prefix sum of the first \(h\) cells in column \(j\) (boundary column heights are treated as \(0\)).
Let \(f[h_1][h_2]\) be the maximum score after processing column \(j\) with \(k[j] = h_1\) and \(k[j-1] = h_2\). When choosing the next height \(hp = k[j+1]\):
Split the transition into \(h_2 \le hp\) and \(h_2 > hp\), and maintain prefix / suffix maxima so that each column costs \(O(n^2)\) instead of \(O(n^3)\).
The time complexity is \(O(n^3)\), and the space complexity is \(O(n^2)\), where \(n\) is the grid size.