LeetCode solutions

2145. Grid Game

My accepted Python solution to LeetCode problem 2145, Grid Game, running in 81ms.

  • Difficulty: Medium
  • Python
  • Runtime 81ms
  • Memory 29.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 81ms, memory 29.8MB, accepted 2026-01-01.

python
class Solution:
    def gridGame(self, grid: List[List[int]]) -> int:
        n = len(grid[0])
        
        # Calculate prefix sums for row 1 (from right)
        # and prefix sums for row 2 (from left)
        
        # top_sum[i] = sum of grid[0][i+1:] (sum to the right of position i in top row)
        # bottom_sum[i] = sum of grid[1][0:i] (sum to the left of position i in bottom row)
        
        top_sum = sum(grid[0])
        bottom_sum = 0
        
        result = float('inf')
        
        for i in range(n):
            # First robot goes down at position i
            # Remove grid[0][i] from top_sum
            top_sum -= grid[0][i]
            
            # Second robot's best choice is max of:
            # 1. Go along top row (collecting top_sum = grid[0][i+1:])
            # 2. Go along bottom row first (collecting bottom_sum = grid[1][0:i])
            second_robot_points = max(top_sum, bottom_sum)
            
            result = min(result, second_robot_points)
            
            # Add grid[1][i] to bottom_sum for next iteration
            bottom_sum += grid[1][i]
        
        return result

Source