877. Stone Game

Question

CleanShot 2024-10-19 at 16.48.09@2x.png

Code

class Solution:
    def stoneGame(self, piles: List[int]) -> bool:
        # Also can return True straight away, since Alice and make choices intentionally to choose all the even piles or all the odd piles

        dp = {}

        def recursion(left, right, is_alice):
            if left > right:
                return 0

            if (left, right) in dp:
                return dp[(left, right)]

			# Remove the result in case of Bob's turn
            l = piles[left] if is_alice else 0
            r = piles[right] if is_alice else 0

            dp[(left, right)] = max(recursion(left + 1, right, not is_alice) + l, 
                                recursion(left, right - 1, not is_alice), r)
                        
            return dp[(left, right)]

        return recursion(0, len(piles) - 1, True) > sum(piles) // 2