Skip to content

Commit fa4a583

Browse files
committed
Add solution #2017
1 parent cd88e69 commit fa4a583

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@
417417
2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy|
418418
2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy|
419419
2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy|
420+
2017|[Grid Game](./2017-grid-game.js)|Medium|
420421
2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy|
421422
2037|[Minimum Number of Moves to Seat Everyone](./2037-minimum-number-of-moves-to-seat-everyone.js)|Easy|
422423
2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy|

solutions/2017-grid-game.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
 (0)