n
be the number of stones.dp
of size n + 1
.dp[n] = 0
(the base case of the DP).i
from n - 1
to 0
:
dp[i] = stoneValue[i] - dp[i + 1]
(take one stone).i + 2 <= n
, update dp[i]
with stoneValue[i] + stoneValue[i + 1] - dp[i + 2]
(take two stones) if it's larger.i + 3 <= n
, update dp[i]
with stoneValue[i] + stoneValue[i + 1] + stoneValue[i + 2] - dp[i + 3]
(take three stones) if it's larger.dp[0] > 0
, Alice wins.dp[0] < 0
, Bob wins.dp[0] = 0
, it is a tie.