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 Operations1. Initial Grid (All White)1234567892. After Operations123456789Heights: [2, 1, 0]3. Score CalculationRed cells score points:Cell (1,1) = 5 (adjacent to black)Cell (2,0) = 7 (adjacent to black)Total Score = 5 + 7 = 12🎯 Key Insight: Score comes from white cells adjacent to black boundariesFind optimal column heights to maximize adjacent scoring opportunities
Understanding the Visualization
1
Input Grid
3x3 grid with values, all cells initially white
2
Paint Columns
Paint columns from top down to different heights
3
Calculate Score
Score from white cells adjacent to black cells
Key Takeaway
🎯 Key Insight: Optimal column heights create maximum scoring boundaries between black and white cells
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