Dynamic Programming21 sections · 916 units
Open in Course

Stone Game IV - Problem Statement

Perfect square moves

nn stones. Each turn, remove a perfect square number of stones (11, 44, 99, ...). Can't move = lose. dp[0]=falsedp[0] = false. dp[k2]=truedp[k^2] = true for all kk (take all, opponent gets 0). Transition: dp[n]=k2n¬dp[nk2]dp[n] = \bigvee_{k^2 \leq n} \lnot dp[n - k^2]. Try all valid square moves. Time: O(nn)O(n \sqrt{n}).

Time complexity: O(nn)O(n \sqrt{n}). For each state, try O(n)O(\sqrt{n}) moves. No simple closed form like Nim or Divisor Game. Unlike Nim, this has no simple closed form. The DP is necessary to determine winning positions.

Space complexity: O(n)O(n) for the dp array.