2017. Grid Game - Explanation
Description
Two robots travel across the two-row grid, one after the other. Each starts at the upper-left cell and finishes at the lower-right cell, moving only right or down. The first robot removes all points from every cell on its path, including its starting and ending cells. The second robot then collects the remaining points along its own path; revisiting cells used by the first robot is allowed, but they now hold zero points. The first robot chooses a path to minimize the second robot's score, while the second chooses a path to maximize it. Return the second robot's score when both make optimal choices.
The first diagram hatches the first robot’s chosen path. After those cells become zero, the second diagram hatches a best path for the second robot.
Example 1:
Input: grid = [[1,4,2],[3,2,1]]
Output: 3Explanation: If the first robot moves down at column 1, the remaining grid is [[0,0,2],[3,0,0]]. The second robot can collect at most 3. Moving down at column 0 or 2 instead lets the second collect 6 or 5, so 3 is optimal.
Example 2:
Input: grid = [[5],[7]]
Output: 0Explanation: Both robots must visit both cells. The first clears them, leaving the second a score of 0.
Example 3:
Input: grid = [[1,1],[9,1]]
Output: 1Explanation: The first robot moves down immediately, clearing the entire bottom row and the first top cell. Only 1 point remains, which the second robot can collect by moving right before moving down.
Constraints:
grid.length == 2- Both rows have the same length, between
1and50000. 1 <= grid[r][c] <= 100000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Prefix Sums - Computing range sums efficiently in O(1) time after O(n) preprocessing
- Game Theory / Minimax - Understanding how to minimize the opponent's maximum gain rather than maximizing your own score
- 2D Grid Traversal - Reasoning about constrained movement paths in a grid (only right and down moves)
1. Brute Force
Intuition
Robot 1 must go right along row 0, drop down to row 1 at some column, then continue right. After Robot 1 collects its points (setting those cells to 0), Robot 2 follows optimally. Robot 1 wants to minimize Robot 2's maximum possible score. We try every possible column where Robot 1 drops down and simulate Robot 2's best response.
Algorithm
- For each column
iwhere Robot 1 drops down:- Calculate the points Robot 1 collects along the top row until column
i, then the bottom row from columnionward. - Simulate Robot 2's optimal path through the remaining grid (top row after
i, bottom row beforei). - Track Robot 2's maximum score for this configuration.
- Calculate the points Robot 1 collects along the top row until column
- Return the minimum of Robot 2's maximum scores across all choices of
i.
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
cols = len(grid[0])
res = float('inf')
top1 = 0
for i in range(cols):
top1 += grid[0][i]
bottom1 = 0
for j in range(i, cols):
bottom1 += grid[1][j]
top2 = robot2 = 0
for j in range(cols):
if j > i:
top2 += grid[0][j]
bottom2 = 0
for k in range(j, i):
bottom2 += grid[1][k]
robot2 = max(robot2, top2 + bottom2)
res = min(res, robot2)
return resTime & Space Complexity
- Time complexity:
- Space complexity:
2. Prefix Sum
Intuition
After Robot 1 drops at column i, Robot 2 can only collect from two disjoint regions: the top row after column i, or the bottom row before column i. Robot 2 will choose whichever region has more points. Using prefix sums, we can compute these region totals in O(1) per column.
Algorithm
- Build prefix sums for both rows.
- For each column
iwhere Robot 1 drops:top = preRow1[N-1] - preRow1[i](sum of top row after columni).bottom = preRow2[i-1]ifi > 0, else0(sum of bottom row before columni).- Robot 2's score is
max(top, bottom).
- Return the minimum of these scores across all
i.
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
N = len(grid[0])
preRow1, preRow2 = grid[0].copy(), grid[1].copy()
for i in range(1, N):
preRow1[i] += preRow1[i - 1]
preRow2[i] += preRow2[i - 1]
res = float("inf")
for i in range(N):
top = preRow1[-1] - preRow1[i]
bottom = preRow2[i - 1] if i > 0 else 0
secondRobot = max(top, bottom)
res = min(res, secondRobot)
return resTime & Space Complexity
- Time complexity:
- Space complexity:
3. Prefix Sum (Space Optimized)
Intuition
We can avoid storing prefix arrays by maintaining running sums. Start with topSum as the total of the top row and bottomSum as 0. As we iterate, subtract from topSum (simulating Robot 1 taking cells from the top) and add to bottomSum (accumulating what Robot 2 could take from below).
Algorithm
- Initialize
topSumas the sum of the entire top row, andbottomSumas0. - For each column
i:- Subtract
grid[0][i]fromtopSum(Robot 1 takes this cell). - Compute Robot 2's best score as
max(topSum, bottomSum). - Update the result with the minimum seen so far.
- Add
grid[1][i]tobottomSum(this cell is now unavailable to Robot 2).
- Subtract
- Return the minimum result.
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
res = float("inf")
topSum = sum(grid[0])
bottomSum = 0
for i in range(len(grid[0])):
topSum -= grid[0][i]
res = min(res, max(topSum, bottomSum))
bottomSum += grid[1][i]
return resTime & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Trying to Maximize Robot 1's Score
A common misunderstanding is thinking Robot 1 should maximize its own score. The problem asks to minimize the score of Robot 2, which is a different objective. Robot 1 must strategically choose where to drop down to leave the least valuable remaining cells for Robot 2, not just greedily collect the most points.
Missing That Robot 2 Has Only Two Disjoint Choices
After Robot 1 drops at column i, Robot 2 can only collect from either the top row after column i OR the bottom row before column i, never both. These regions are mutually exclusive because Robot 2 cannot move left. Failing to recognize this leads to overcounting what Robot 2 can collect.
Integer Overflow with Large Grid Values
The grid values can be up to 10^5 and the grid can have up to 5 * 10^4 columns. The sum of all values can exceed the 32-bit integer limit. Use long or 64-bit integers for the prefix sums and running totals to avoid overflow errors that produce incorrect results.
Sign in to join the discussion