Skip to content
LC-0877 Medium LeetCode

877. Stone Game

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 72% Topics: Array, Math, Dynamic Programming, Game Theory
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n^2)
# Space: O(n)

class Solution(object):
    def stoneGame(self, piles):
        """
        :type piles: List[int]
        :rtype: bool
        """
        if len(piles) % 2 == 0 or len(piles) == 1:
            return True

        dp = [0] * len(piles)
        for i in reversed(xrange(len(piles))):
            dp[i] = piles[i]
            for j in xrange(i+1, len(piles)):
                dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1])
        return dp[-1] >= 0

Solution from kamyu104/LeetCode-Solutions · MIT