-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrid Game.cpp
22 lines (19 loc) · 1.38 KB
/
Grid Game.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Q.- 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.
Approach - Use of prefix sum for each row -
class Solution {
public:
long long gridGame(vector<vector<int>>& grid) {
long long topSum = 0, botSum = 0, min2 = LLONG_MAX;
for (int num : grid[0]) topSum += num;
int n = grid[0].size();
for (int col = 0; col < n; col++) {
topSum -= grid[0][col];
min2 = min(min2, max(topSum, botSum));
botSum += grid[1][col];
}
return min2;
}
};