Similar Problems
Similar Problems not available
Stone Game Iv - Leetcode Solution
Companies:
LeetCode: Stone Game Iv Leetcode Solution
Difficulty: Hard
Topics: math dynamic-programming
Problem statement:
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
Alice and Bob take turns, with Alice starting first. On each turn, the player takes any stone from either the beginning or the end of the row (i.e. from either end, not limited to just the ends), removes it from the row permanently, and receives the value of the stone.
When no more stones are available, the player with the higher score wins. If both players have the same score, the game is a draw. Both players will play optimally.
Given an array of integers stoneValue, return the winner of the game. If Alice wins, return "Alice". If Bob wins, return "Bob". If the game is a draw, return "Tie".
Solution:
This problem can be solved with dynamic programming. We will maintain two dp arrays, dp1 and dp2, where dp1[i] will store the maximum score Alice can get if she starts from the ith index, and dp2[i] will store the maximum score Bob can get if he starts from the ith index.
Let's first initialize dp1 and dp2 with 0, as there are no stones left to pick at the beginning.
Next, we will iterate over each stone in the stoneValue array, starting from the end. For each stone, we will calculate the score that Alice and Bob can get if they start from that index.
To calculate the score that Alice can get, we will try to pick up stones from both ends and recursively calculate the score that Bob can get. We will take the maximum of these scores and add the value of the current stone to it.
Similarly, to calculate the score that Bob can get, we will try to pick up stones from both ends and recursively calculate the score that Alice can get. We will take the minimum of these scores and add the value of the current stone to it.
Finally, we will return the winner based on the scores we have calculated. If Alice's score is greater than Bob's score, we will return "Alice". If Bob's score is greater than Alice's score, we will return "Bob". If the score is a tie, we will return "Tie".
Here is the Python code for the solution:
def stoneGameIV(stoneValue: List[int]) -> str: n = len(stoneValue) dp1 = [0] * (n+1) dp2 = [0] * (n+1)
for i in range(n-1, -1, -1):
alice_score = 0
bob_score = 0
for j in range(i, min(i+3, n)):
alice_score = max(alice_score, stoneValue[j] + dp2[j+1])
for j in range(i, min(i+3, n)):
bob_score = min(bob_score, stoneValue[j] + dp1[j+1])
dp1[i] = alice_score
dp2[i] = bob_score
alice_score = dp1[0]
bob_score = dp2[0]
if alice_score > bob_score:
return "Alice"
elif alice_score < bob_score:
return "Bob"
else:
return "Tie"
Time Complexity: O(n^2)
Space Complexity: O(n)
Stone Game Iv Solution Code
1