Leetcode 2017: Grid Game

grid47
grid47
Exploring patterns and algorithms
Apr 19, 2024 6 min read

You are given a 2D grid of size 2 x n, where each cell contains points. Two robots play a game where they start at (0, 0) and aim to reach (1, n-1). The first robot moves first, collecting points along its path. Then, the second robot moves, trying to maximize the points it collects. The task is to find the number of points collected by the second robot if both play optimally.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D array grid of size 2 x n, where each element grid[r][c] represents the number of points at position (r, c) in the grid.
Example: [[2, 5, 4], [1, 5, 1]]
Constraints:
• grid.length == 2
• n == grid[r].length
• 1 <= n <= 5 * 10^4
• 1 <= grid[r][c] <= 10^5
Output: Return the number of points collected by the second robot after both robots have moved optimally.
Example: 4
Constraints:
• The output should be the total number of points collected by the second robot.
Goal: The goal is to simulate the movement of both robots while ensuring that the first robot minimizes the points collected by the second robot and the second robot maximizes its own points.
Steps:
• Initialize variables to track the points collected by the first and second robots.
• Iterate through each column and update the points for both robots.
• For each robot, calculate the optimal path by updating the number of points in the grid after each robot’s move.
• Return the result of the second robot’s collected points.
Goal: The grid has two rows and n columns, and n can be as large as 50,000.
Steps:
• grid.length == 2
• n == grid[r].length
• 1 <= n <= 5 * 10^4
• 1 <= grid[r][c] <= 10^5
Assumptions:
• The grid will always have two rows and at least one column.
• Both robots will move optimally to achieve their respective goals.
Input: [[2, 5, 4], [1, 5, 1]]
Explanation: The first robot moves optimally to minimize the points collected by the second robot. After its path, the second robot collects 4 points.

Input: [[3, 3, 1], [8, 5, 2]]
Explanation: After the first robot moves, the second robot is left with 4 points on its path, as it maximizes its collection.

Input: [[1, 3, 1, 15], [1, 3, 3, 1]]
Explanation: The second robot collects 7 points after the first robot moves optimally.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus