|
| 1 | +# 1140. Stone Game II |
| 2 | +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. |
| 3 | + |
| 4 | +Alice and Bob take turns, with Alice starting first. |
| 5 | + |
| 6 | +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)`. Initially, M = 1. |
| 7 | + |
| 8 | +The game continues until all the stones have been taken. |
| 9 | + |
| 10 | +Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. |
| 11 | + |
| 12 | +#### Example 1: |
| 13 | +<pre> |
| 14 | +<strong>Input:</strong> piles = [2,7,9,4,4] |
| 15 | +<strong>Output:</strong> 10 |
| 16 | +<strong>Explanation:</strong> |
| 17 | +* 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 stones in total. |
| 18 | +* If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 stones in total. |
| 19 | +So we return 10 since it's larger. |
| 20 | +</pre> |
| 21 | + |
| 22 | +#### Example 2: |
| 23 | +<pre> |
| 24 | +<strong>Input:</strong> piles = [1,2,3,4,5,100] |
| 25 | +<strong>Output:</strong> 104 |
| 26 | +</pre> |
| 27 | + |
| 28 | +#### Constraints: |
| 29 | +* `1 <= piles.length <= 100` |
| 30 | +* <code>1 <= piles[i] <= 10<sup>4</sup></code> |
| 31 | + |
| 32 | +## Solutions (Python) |
| 33 | + |
| 34 | +### 1. Solution |
| 35 | +```Python |
| 36 | +from functools import cache |
| 37 | + |
| 38 | + |
| 39 | +class Solution: |
| 40 | + def stoneGameII(self, piles: List[int]) -> int: |
| 41 | + @cache |
| 42 | + def subGame(m: int, i: int) -> int: |
| 43 | + if i == len(piles): |
| 44 | + return 0 |
| 45 | + |
| 46 | + total = sum(piles[i:]) |
| 47 | + |
| 48 | + return total - min(subGame(max(m, x), i + x) for x in range(1, min(2 * m, len(piles) - i) + 1)) |
| 49 | + |
| 50 | + return subGame(1, 0) |
| 51 | +``` |
0 commit comments