Leetcode: Stone Game (How can I code it differently)

Question:

Problem statement:

Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.

Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.

Here is my implementation:

def stoneGame(self, piles: List[int]) -> bool:
        # return the the score difference between alice and bob(alice - bob)
        def dfs(turn, i, j):
            if i > j: #no more stone left
                return 0
            
            if turn == "alice": #alice tries to maximize her score
                choice1 = piles[i] + dfs("bob", i+1, j)
                choice2 = piles[j] + dfs("bob", i, j-1)
                return max(choice1, choice2)
            
            if turn == "bob": #bob tries to minimize alice's score, bob's score is negative because I want to subtract it from alice
                choice1 = -piles[i] + dfs("alice", i+1, j)
                choice2 = -piles[j] + dfs("alice", i, j-1)
                return min(choice1, choice2) #take the smallest and subtract it from alice. 
        
        
        return (dfs("alice", 0, len(piles)-1)) > 0
        #if alice - bob > 0, that means alice has more points so she wins

I solve it by calculating the net different between alice and bob. How can I change my code so that I’m able to record alice’s and bob’s score instead of just keeping track of their difference.

Asked By: Michael Xia

||

Answers:

There’s an O(1) solution: Alice always wins.

Imagine the piles are numbered from 1 to n for n some even number.

Then, either the even piles or the odd piles collectively have more stones.

Whichever parity has more stones is what Alice always picks, and Bob is forced to pick the other parity.

Now, while Alice needs to do O(n) work to execute this strategy, knowing that she has a winning strategy and so will win takes no work.

Answered By: Dave