|
| 1 | +/** |
| 2 | + * 2017. Grid Game |
| 3 | + * https://leetcode.com/problems/grid-game/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number |
| 7 | + * of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. |
| 8 | + * |
| 9 | + * Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move |
| 10 | + * to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). |
| 11 | + * |
| 12 | + * At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the |
| 13 | + * points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is |
| 14 | + * set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its |
| 15 | + * path. Note that their paths may intersect with one another. |
| 16 | + * |
| 17 | + * The first robot wants to minimize the number of points collected by the second robot. In |
| 18 | + * contrast, the second robot wants to maximize the number of points it collects. If both |
| 19 | + * robots play optimally, return the number of points collected by the second robot. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} grid |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var gridGame = function(grid) { |
| 27 | + let result = Infinity; |
| 28 | + let sum1 = grid[0].reduce((a, b) => a + b, 0); |
| 29 | + let sum2 = 0; |
| 30 | + |
| 31 | + for (let i = 0; i < grid[0].length; i++) { |
| 32 | + sum1 -= grid[0][i]; |
| 33 | + result = Math.min(result, Math.max(sum1, sum2)); |
| 34 | + sum2 += grid[1][i]; |
| 35 | + } |
| 36 | + |
| 37 | + return result; |
| 38 | +}; |
0 commit comments