Skip to content

Commit 857ad57

Browse files
committed
Add solution #1140
1 parent b80b8b4 commit 857ad57

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,149 LeetCode solutions in JavaScript
1+
# 1,150 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -896,6 +896,7 @@
896896
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
897897
1138|[Alphabet Board Path](./solutions/1138-alphabet-board-path.js)|Medium|
898898
1139|[Largest 1-Bordered Square](./solutions/1139-largest-1-bordered-square.js)|Medium|
899+
1140|[Stone Game II](./solutions/1140-stone-game-ii.js)|Medium|
899900
1143|[Longest Common Subsequence](./solutions/1143-longest-common-subsequence.js)|Medium|
900901
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
901902
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|

solutions/1140-stone-game-ii.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 1140. Stone Game II
3+
* https://leetcode.com/problems/stone-game-ii/
4+
* Difficulty: Medium
5+
*
6+
* Alice and Bob continue their games with piles of stones. There are a number of piles arranged
7+
* in a row, and each pile has a positive integer number of stones piles[i]. The objective of
8+
* the game is to end with the most stones.
9+
*
10+
* Alice and Bob take turns, with Alice starting first.
11+
*
12+
* On each player's turn, that player can take all the stones in the first X remaining piles,
13+
* where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1.
14+
*
15+
* The game continues until all the stones have been taken.
16+
*
17+
* Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
18+
*/
19+
20+
/**
21+
* @param {number[]} piles
22+
* @return {number}
23+
*/
24+
var stoneGameII = function(piles) {
25+
const n = piles.length;
26+
const cache = new Map();
27+
const suffixSums = new Array(n + 1).fill(0);
28+
29+
for (let i = n - 1; i >= 0; i--) {
30+
suffixSums[i] = suffixSums[i + 1] + piles[i];
31+
}
32+
33+
return maxStones(0, 1);
34+
35+
function maxStones(index, m) {
36+
if (index >= n) return 0;
37+
if (2 * m >= n - index) return suffixSums[index];
38+
39+
const key = `${index},${m}`;
40+
if (cache.has(key)) return cache.get(key);
41+
42+
let opponentMin = Infinity;
43+
for (let x = 1; x <= 2 * m; x++) {
44+
opponentMin = Math.min(opponentMin, maxStones(index + x, Math.max(m, x)));
45+
}
46+
47+
const result = suffixSums[index] - opponentMin;
48+
cache.set(key, result);
49+
return result;
50+
}
51+
};

0 commit comments

Comments
 (0)