Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1140 Stone Game II - State Design

Dp[i][M]

dp[i][M]dp[i][M] = maximum stones the current player can collect from piles [i,n1][i, n-1] when the parameter is MM. Base case: if ini \geq n, no piles left, return 00.

If i+2Mni + 2M \geq n, current player takes all remaining piles. Transition: try taking XX piles for X=1X = 1 to 2M2M. Stones I get = suffix[i][i] - suffix[i+X][i + X]. Then opponent plays from i+Xi + X with M=max(M,X)M' = \max(M, X). My total = stones taken ++ (remaining - opponent's best).