Dynamic Programming21 sections · 915 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,n−1][i, n-1] when the parameter is MM. Base case: if i≥ni \geq n, no piles left, return 00.

If i+2M≥ni + 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).