All problems
0520MediumArrayDynamic ProgrammingMatrix

Strongest Signal Across the Amplifier Grid

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1594Maximum Non Negative Product in a Matrix

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 test rig is a rectangular board of amplifier tiles, given as grid, where grid[r][c] is the gain of the tile in row r and column c. A gain may be negative, which means that tile inverts the signal.

A probe signal enters at the top-left tile with value 1 and must leave at the bottom-right tile. From a tile the probe may only step one tile to the right or one tile down. Every tile the probe occupies, including the entry tile and the exit tile, multiplies the running value by that tile's gain.

Among the routes whose final value is not negative, report the largest final value. Because that value can be enormous, report it modulo 1000000007. If every route ends on a negative value, return -1 instead.

Examples

Example 1

Input
grid = [[-2, 3], [4, -1]]
Output
8

Stepping down and then right puts the probe on -2, 4 and -1, so the value leaving the board is 8. That is not negative, and 8 reduced modulo 1000000007 is 8.

Example 2

Input
grid = [[2, -1, -1, 3, 1, 2]]
Output
12

The board is a single row, so the probe walks every tile: 2, -1, -1, 3, 1 and 2 multiply to 12.

Example 3

Input
grid = [[-1, 2], [3, 4]]
Output
-1

The two available routes leave the board holding -8 and -12. Neither is allowed, so the answer is -1.

Constraints

  • rows == grid.length
  • cols == grid[r].length
  • 1 <= rows, cols <= 15
  • -4 <= grid[r][c] <= 4
  • The reported value is the largest non-negative final value reduced modulo 1000000007, or -1.

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 max_product_path(grid: list[list[int]]) -> int:
Java
public int maxProductPath(int[][] grid)
September 7
Apply