You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1600-1699/1690.Stone Game VII/README_EN.md
+140-1
Original file line number
Diff line number
Diff line change
@@ -65,7 +65,7 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$
65
65
classSolution:
66
66
defstoneGameVII(self, stones: List[int]) -> int:
67
67
@cache
68
-
defdfs(i, j):
68
+
defdfs(i: int, j: int) -> int:
69
69
if i > j:
70
70
return0
71
71
a = s[j +1] - s[i +1] - dfs(i +1, j)
@@ -161,6 +161,145 @@ func stoneGameVII(stones []int) int {
161
161
}
162
162
```
163
163
164
+
```ts
165
+
function stoneGameVII(stones:number[]):number {
166
+
const n =stones.length;
167
+
const s:number[] =Array(n+1).fill(0);
168
+
for (let i =0; i<n; ++i) {
169
+
s[i+1] =s[i] +stones[i];
170
+
}
171
+
const f:number[][] =Array.from({ length: n }, () =>Array(n).fill(0));
172
+
const dfs = (i:number, j:number):number=> {
173
+
if (i>j) {
174
+
return0;
175
+
}
176
+
if (f[i][j]) {
177
+
returnf[i][j];
178
+
}
179
+
const a =s[j+1] -s[i+1] -dfs(i+1, j);
180
+
const b =s[j] -s[i] -dfs(i, j-1);
181
+
return (f[i][j] =Math.max(a, b));
182
+
};
183
+
returndfs(0, n-1);
184
+
}
185
+
```
186
+
187
+
<!-- tabs:end -->
188
+
189
+
### Solution 2: Dynamic Programming
190
+
191
+
We can convert the memoization search in Solution 1 into dynamic programming. We define $f[i][j]$ as the score difference between the first and second players when the remaining stones are $stones[i], stones[i + 1], \dots, stones[j]$. Therefore, the answer is $f[0][n - 1]$.
When calculating $f[i][j]$, we need to ensure that $f[i + 1][j]$ and $f[i][j - 1]$ have been calculated. Therefore, we need to enumerate $i$ in descending order and $j$ in ascending order.
200
+
201
+
Finally, the answer is $f[0][n - 1]$.
202
+
203
+
The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of stones.
0 commit comments