All problems
0492HardArrayDynamic ProgrammingMatrixPrefix Sum

Terrace Soak Yield

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3225Maximum Score From Grid Operations

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def best_soak_payout(grid: list[list[int]]) -> int:
Java
public long bestSoakPayout(int[][] grid)
September 7
Apply