[LeetCode] Grid Game

2017. Grid Game

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.

Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).

At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.

The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
long long gridGame(vector<vector<int>>& grid) {
int n = 2, m = grid[0].size();
vector<long long> dp(m + 1), dpp(m + 1);
for(int i = 0; i < m; i++) {
dp[i+1] = dp[i] + grid[0][i];
dpp[i+1] = dpp[i] + grid[1][i];
}
long long res = LLONG_MAX;
for(int i = 0; i < m; i++) {
long long up = dp[m] - dp[i+1];
long long down = dpp[i];
long long ma = max(up,down);
res = min(res, ma);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/11/PS/LeetCode/grid-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.