Grid Game

You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.

Both robots initially start at (0, 0) and want to reach (1, n - 1). Each robot may only move:

  • To the right, from (r, c) to (r, c + 1).
  • Down, from (r, c) to (r + 1, c).

At the start of the game, the first robot moves from (0, 0) to (1, n - 1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n - 1), collecting the points on its path. Note that their paths may intersect with one another.

The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.

Example 1
2 5 4
1 5 1
Inputgrid = [[2,5,4],[1,5,1]]
Output4
After the first robot zeros its optimal path, the second robot will collect 0 + 0 + 4 + 0 = 4 points.
Example 2
3 3 1
8 5 2
Inputgrid = [[3,3,1],[8,5,2]]
Output4
After the first robot zeros its optimal path, the second robot will collect 0 + 3 + 1 + 0 = 4 points.

Constraints

  • grid.length == 2
  • n == grid[r].length
  • 1 <= n <= 5 * 10^4
  • 1 <= grid[r][c] <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate