#2017
Grid Game
MediumArrayMatrixPrefix SumPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages prefix sums to efficiently calculate the maximum points the second robot can collect after the first robot has made its move. By precomputing the prefix sums, we can quickly determine the points collected by the second robot without simulating every path.
⚙️
Algorithm
4 steps- 1Step 1: Compute prefix sums for both rows to facilitate quick calculations of points collected.
- 2Step 2: For each possible column index where the first robot can move down, calculate the total points collected by the second robot using the prefix sums.
- 3Step 3: The total points for the second robot is the sum of points in the first row up to the index and the second row from that index to the end.
- 4Step 4: Keep track of the maximum points collected by the second robot across all possible paths of the first robot.
solution.py14 lines
1def gridGame(grid):
2 n = len(grid[0])
3 prefix_row1 = [0] * n
4 prefix_row2 = [0] * n
5 prefix_row1[0] = grid[0][0]
6 prefix_row2[0] = grid[1][0]
7 for i in range(1, n):
8 prefix_row1[i] = prefix_row1[i-1] + grid[0][i]
9 prefix_row2[i] = prefix_row2[i-1] + grid[1][i]
10 max_points = 0
11 for i in range(n):
12 points = prefix_row1[i] + (prefix_row2[n-1] - prefix_row2[i])
13 max_points = max(max_points, points)
14 return max_pointsℹ
Complexity note: The time complexity is O(n) because we compute prefix sums in a single pass and then evaluate the points in another pass, leading to a linear complexity overall.
- 1Understanding the impact of the first robot's path on the second robot's collection is crucial.
- 2Using prefix sums allows for efficient calculation of points without redundant computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.