-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path1140-stone-game-ii.kt
More file actions
29 lines (25 loc) · 857 Bytes
/
1140-stone-game-ii.kt
File metadata and controls
29 lines (25 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
fun stoneGameII(piles: IntArray): Int {
val dp = Array (2) { Array (piles.size) { IntArray (piles.size + 1) } }
fun bfs(a: Int, i: Int, m: Int): Int {
if (i == piles.size)
return 0
if (dp[a][i][m] != 0)
return dp[a][i][m]
var res = if (a == 0) 0 else Integer.MAX_VALUE
var total = 0
for (x in 1..(2 * m)) {
if (i + x > piles.size)
break
total += piles[i + x - 1]
if (a == 0)
res = maxOf(res, total + bfs(1, i + x, maxOf(m, x)))
else
res = minOf(res, bfs(0, i + x, maxOf(m, x)))
}
dp[a][i][m] = res
return dp[a][i][m]
}
return bfs(0, 0, 1)
}
}