Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eea7940

Browse files
Time: 1456 ms (7.14%), Space: 17.1 MB (79.59%) - LeetHub
1 parent e27ce3d commit eea7940

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def stoneGameII(self, piles: List[int]) -> int:
3+
n = len(piles)
4+
dp = [[0] * (n + 1) for _ in range(n + 1)]
5+
suffix_sum = [0] * (n + 1)
6+
7+
# Calculate suffix sums to efficiently compute the sum of any subarray
8+
for i in range(n - 1, -1, -1):
9+
suffix_sum[i] = suffix_sum[i + 1] + piles[i]
10+
11+
# Bottom-up dynamic programming
12+
for i in range(n - 1, -1, -1):
13+
for M in range(1, n + 1):
14+
for X in range(1, min(2 * M, n - i) + 1):
15+
dp[i][M] = max(dp[i][M], suffix_sum[i] - dp[i + X][max(M, X)])
16+
17+
return dp[0][1]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /