Skip to content

Commit 868c13b

Browse files
committed
feat: solve No.1140
1 parent 5822ab7 commit 868c13b

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

1101-1200/1140. Stone Game II.md

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# 1140. Stone Game II
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Math, Dynamic Programming, Prefix Sum, Game Theory.
5+
- Similar Questions: Stone Game V, Stone Game VI, Stone Game VII, Stone Game VIII, Stone Game IX.
6+
7+
## Problem
8+
9+
Alice and Bob continue their games with piles of stones.  There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`.  The objective of the game is to end with the most stones. 
10+
11+
Alice and Bob take turns, with Alice starting first.  Initially, `M = 1`.
12+
13+
On each player's turn, that player can take **all the stones** in the **first** `X` remaining piles, where `1 <= X <= 2M`.  Then, we set `M = max(M, X)`.
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+
Example 1:
21+
22+
```
23+
Input: piles = [2,7,9,4,4]
24+
Output: 10
25+
Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.
26+
```
27+
28+
Example 2:
29+
30+
```
31+
Input: piles = [1,2,3,4,5,100]
32+
Output: 104
33+
```
34+
35+
 
36+
**Constraints:**
37+
38+
39+
40+
- `1 <= piles.length <= 100`
41+
42+
- `1 <= piles[i] <= 104`
43+
44+
45+
46+
## Solution
47+
48+
```javascript
49+
/**
50+
* @param {number[]} piles
51+
* @return {number}
52+
*/
53+
var stoneGameII = function(piles) {
54+
var dp = Array(piles.length).fill(0).map(() => ({}));
55+
var suffixSum = Array(piles.length);
56+
for (var i = piles.length - 1; i >= 0; i--) {
57+
suffixSum[i] = (suffixSum[i + 1] || 0) + piles[i];
58+
}
59+
return helper(piles, 0, 1, dp, suffixSum);
60+
};
61+
62+
var helper = function(piles, i, M, dp, suffixSum) {
63+
if (dp[i][M]) return dp[i][M];
64+
var res = 0;
65+
var sum = 0;
66+
for (var j = 0; j < 2 * M && i + j < piles.length; j++) {
67+
sum += piles[i + j];
68+
res = Math.max(
69+
res,
70+
i + j + 1 === piles.length
71+
? sum
72+
: sum + suffixSum[i + j + 1] - helper(piles, i + j + 1, Math.max(M, j + 1), dp, suffixSum)
73+
);
74+
}
75+
dp[i][M] = res;
76+
return res;
77+
}
78+
```
79+
80+
**Explain:**
81+
82+
nope.
83+
84+
**Complexity:**
85+
86+
* Time complexity : O(n ^ 3).
87+
* Space complexity : O(n ^ 2).

0 commit comments

Comments
 (0)