Skip to content

Commit a058fb4

Browse files
authored
Create 1140-stone-game-ii.kt
1 parent 77eb332 commit a058fb4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

kotlin/1140-stone-game-ii.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
fun stoneGameII(piles: IntArray): Int {
3+
val dp = Array (2) { Array (piles.size) { IntArray (piles.size + 1) } }
4+
5+
fun bfs(a: Int, i: Int, m: Int): Int {
6+
if (i == piles.size)
7+
return 0
8+
if (dp[a][i][m] != 0)
9+
return dp[a][i][m]
10+
11+
var res = if (a == 0) 0 else Integer.MAX_VALUE
12+
var total = 0
13+
for (x in 1..(2 * m)) {
14+
if (i + x > piles.size)
15+
break
16+
total += piles[i + x - 1]
17+
if (a == 0)
18+
res = maxOf(res, total + bfs(1, i + x, maxOf(m, x)))
19+
else
20+
res = minOf(res, bfs(0, i + x, maxOf(m, x)))
21+
}
22+
23+
dp[a][i][m] = res
24+
return dp[a][i][m]
25+
}
26+
27+
return bfs(0, 0, 1)
28+
}
29+
}

0 commit comments

Comments
 (0)