Maximum Score From Grid Operations
Real-world version: Terrace Soak YieldThe statement here is our own: the same inputs, outputs and technique.
A hillside terrace is laid out as an n by n block of plots. grid[r][c] is the crop value of the plot in row r and column c, with row 0 along the top edge.
Before the season starts you fix, for each column c on its own, a soak depth between 0 and n. Water poured into a column soaks the top plots of that column, so a depth of d leaves rows 0 through d - 1 of that column soaked and every row from d downwards dry. A depth of 0 leaves the whole column dry and a depth of n soaks all of it.
At harvest a plot pays out its crop value only when both of these hold:
- the plot itself is dry, and
- the plot immediately to its left or the plot immediately to its right, in the same row, is soaked.
A soaked plot pays out nothing, and neither does a dry plot whose horizontal neighbours are all dry. Plots in the leftmost and rightmost columns have a single horizontal neighbour.
Return the largest total payout you can arrange by choosing the depths.
Examples
Example 1
- Input
- grid = [[5, 0], [0, 0]]
- Output
- 5
Soaking the right column to depth 1 and leaving the left column dry makes the plot worth 5 a dry plot with a soaked neighbour, so it pays out.
Example 2
- Input
- grid = [[0, 9, 0], [0, 0, 0], [0, 9, 0]]
- Output
- 18
Soaking the outer two columns all the way down leaves the middle column dry with soaked plots on both sides in every row, so both plots worth 9 pay out.
Example 3
- Input
- grid = [[41]]
- Output
- 0
A single column has no horizontal neighbour at all, so whatever depth is chosen nothing pays out.
Constraints
- 1 <= n == grid.length <= 100
- n == grid[i].length
- 0 <= grid[i][j] <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def best_soak_payout(grid: list[list[int]]) -> int:public long bestSoakPayout(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's