Grid Game — LeetCode 2017 Python Solution
- Problem
- #2017
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- grid = [[2,5,4],[1,5,1]]
- Output
- 4
- Explanation
- The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
Python solution
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
ans = inf
s1, s2 = sum(grid[0]), 0
for j, v in enumerate(grid[0]):
s1 -= v
ans = min(ans, max(s1, s2))
s2 += grid[1][j]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2017. Grid Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2017. Grid Game?
- LeetCode 2017. Grid Game is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2017. Grid Game?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2017. Grid Game?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2017. Grid Game cover?
- LeetCode 2017. Grid Game is tagged Array, Matrix and Prefix Sum on LeetCode.