Maximum Score From Grid Operations - Problem

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 j-th column starting from the top row down to the i-th 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.

Input & Output

Example 1 — Basic 3x3 Grid
$ Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
💡 Note: Color columns with heights [2,1,0]. White cells (2,0)=7 and (1,1)=5 are adjacent to black cells, giving score 7+5=12. Actually optimal is different configuration giving 13.
Example 2 — Small 2x2 Grid
$ Input: grid = [[1,2],[3,4]]
Output: 4
💡 Note: With heights [1,0], cell (1,1)=4 is white and adjacent to black cell at (0,1), giving score 4.
Example 3 — All Same Values
$ Input: grid = [[1,1],[1,1]]
Output: 1
💡 Note: Best configuration gives score 1 from one white cell adjacent to black.

Constraints

  • 1 ≤ n ≤ 102
  • 1 ≤ grid[i][j] ≤ 105

Visualization

Tap to expand
Maximum Score From Grid Operations INPUT 3x3 Matrix Grid 1 2 3 4 5 6 7 8 9 j=0 j=1 j=2 i=0 i=1 i=2 grid = [[1,2,3], [4,5,6],[7,8,9]] n = 3 (grid size) All cells start WHITE Color columns from top ALGORITHM STEPS 1 Define State dp[col][height] = max score for columns 0 to col 2 Transition For each column height, compute adjacent white cells 3 Score Calculation White cell scores if adjacent to black column 4 Optimal Choice Color col 0 to row 2 Keep col 1,2 white 1 2 3 4 5 6 7 8 6 Black=colored, Green=scoring FINAL RESULT Optimal Configuration 1 2 3 4 5 6 7 8 6 Score Calculation: Cell(1,1)=5 adjacent to black Cell(2,1)=8 adjacent to black Total: 5 + 8 = 13 Output: 13 Key Insight: Use dynamic programming with state dp[col][black_height] to track maximum achievable score. For each column, decide how many cells to color black from top. A white cell scores only if it has a horizontally adjacent black cell. Optimize by considering all possible height combinations. TutorialsPoint - Maximum Score From Grid Operations | Optimal Solution
Asked in
Google 25 Microsoft 18
25.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen