Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1140 Stone Game II - Walkthrough

Tracing with M parameter

Piles: [2,7,9,4,4][2, 7, 9, 4, 4]. Player can take first 11 to 2M2M piles. MM starts at 1, updates to max(M,X)\max(M, X) after taking XX piles. dp[i][M]dp[i][M] = max stones current player can get from piles [i:][i:] with parameter MM. From dp[0][1]dp[0][1]: can take 1 pile (get 2) or 2 piles (get 9).

After taking XX, opponent gets dp[i+X][max(M,X)]dp[i+X][\max(M,X)], I get the rest. observation: I get suffixSum[i]dp[i+X][max(M,X)]suffixSum[i] - dp[i+X][\max(M,X)]. The opponent's best becomes my loss. Find the largest over valid XX.