Skip to content

Commit f3f65ec

Browse files
committed
Time: 134 ms (94.90%), Space: 16.8 MB (98.78%) - LeetHub
1 parent c810e36 commit f3f65ec

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# time complexity:O(n^3)
2+
# space complexity: O(n^2)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def stoneGameII(self, piles: List[int]) -> int:
8+
memo = [[0] * len(piles) for _ in range(len(piles))]
9+
suffixSum = piles[:]
10+
11+
for i in range(len(suffixSum) - 2, -1, -1):
12+
suffixSum[i] += suffixSum[i + 1]
13+
14+
return self.max_stones(suffixSum, 1, 0, memo)
15+
16+
def max_stones(
17+
self,
18+
suffixSum: List[int],
19+
maxTillNow: int,
20+
currIndex: int,
21+
memo: List[List[int]],
22+
) -> int:
23+
if currIndex + 2 * maxTillNow >= len(suffixSum):
24+
return suffixSum[currIndex]
25+
26+
if memo[currIndex][maxTillNow] > 0:
27+
return memo[currIndex][maxTillNow]
28+
29+
res = float("inf")
30+
31+
for i in range(1, 2 * maxTillNow + 1):
32+
res = min(
33+
res,
34+
self.max_stones(
35+
suffixSum,
36+
max(i, maxTillNow),
37+
currIndex + i,
38+
memo,
39+
),
40+
)
41+
42+
memo[currIndex][maxTillNow] = suffixSum[currIndex] - res
43+
return memo[currIndex][maxTillNow]
44+
45+
46+
piles = [2, 7, 9, 4, 4]
47+
print(Solution().stoneGameII(piles))

0 commit comments

Comments
 (0)