Maximum Score From Grid Operations - Problem

Imagine you're a digital artist working with a special painting grid! You start with an n ร— n white canvas and have a unique brush that can paint entire columns from top to bottom.

Here's how your magical brush works: when you select any cell at position (i, j), it colors all cells black in column j from the top row (row 0) down to row i inclusive.

The scoring system is fascinating: You earn points equal to the value of each white cell that has at least one horizontally adjacent black cell (left or right neighbor).

Your mission: Maximize your total score by strategically choosing which cells to paint!

Input: A 2D matrix grid of size n ร— n containing positive integers
Output: The maximum possible score you can achieve

Input & Output

example_1.py โ€” Basic Example
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
โ€บ Output: 4
๐Ÿ’ก Note: Paint column 1 completely (height 3). This creates white cells at positions (0,0), (1,0), (2,0), (0,2), (1,2), (2,2) with black horizontal neighbors. Each contributes score 1, but we only count horizontal adjacencies, giving us a score of 4.
example_2.py โ€” Strategic Painting
$ Input: grid = [[2,3,4],[5,6,7],[8,9,1]]
โ€บ Output: 22
๐Ÿ’ก Note: Optimal strategy involves painting column 0 to height 2 and column 1 to height 1. This creates strategic boundaries that maximize the sum of white cells with black neighbors.
example_3.py โ€” Single Column Edge Case
$ Input: grid = [[5]]
โ€บ Output: 0
๐Ÿ’ก Note: With only one column, no cell can have a horizontal neighbor, so the maximum score is 0.

Constraints

  • 1 โ‰ค n โ‰ค 100
  • 1 โ‰ค grid[i][j] โ‰ค 105
  • The grid is always square (n ร— n)
  • Time limit: 3 seconds

Visualization

Tap to expand
532461789Red circles show scoring white cellswith black horizontal neighborsColumn 1 painted to height 2Score = 5 + 3 + 1 = 9Paint Roller Effect
Understanding the Visualization
1
Choose Painting Heights
For each column, decide how far down to paint (0 to n rows)
2
Create Boundaries
White-black boundaries form horizontally between adjacent columns
3
Calculate Score
Sum values of white cells that have black horizontal neighbors
4
Optimize Configuration
Use DP to find the height combination that maximizes total score
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution balances creating valuable boundaries while maximizing the sum of white cells adjacent to black regions through strategic column height selection.
Asked in
Google 45 Meta 38
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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