Program to find minimum difference of stone games score in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called stones where stones[i] represents the value of the ith stone from the left. Two friends Amal and Bimal re playing a turn based game with these stones and Amal starts first always. There are n stones arranged in a row. Each player can remove either the leftmost stone or the rightmost stone from the row and get points equal to the sum of the remaining stones' values in the row. Who will get the higher score will win. Now, Bimal found that he will always lose this game, so he decided to minimize the score's difference. Amal's goal is to maximize the difference in the score. So we have to find the difference in Amal and Bimal's score if they both play optimally.

So, if the input is like stones = [6,4,2,5,3], then the output will be 6 because Amal can take 3, so his score will be 6+4+2+5 = 17, Bimal's score 0 so far, and array is like [6,4,2,5], then Bimal takes 6 so his score 4+2+5 = 11, now array is [4,2,5]. Then Amal removes 4, so his score 17+2+5 = 24, stone array [2,5] Bob removes 2, so his score 11+5 = 16, current stone array [5] and Amal removes last stone with value 5 and got 0 score, so his final score 24 + 0 = 24. So the difference of their scores is 24-16 = 8.

To solve this, we will follow these steps −

• n := size of stones
• dp := an array of size n and fill with 0
• for i in range n - 1 to 0, decrease by 1, do
• v := stones[i]
• run_sum := 0
• for j in range i + 1 to n - 1, do
• new_run := run_sum + stones[j]
• dp[j] := (maximum of new_run - dp[j]) and (run_sum+v - dp[j - 1])
• run_sum := new_run
• return dp[n - 1]

Example

Let us see the following implementation to get better understanding −

def solve(stones):
n = len(stones)
dp = [0] * n

for i in range(n - 1, -1, -1):
v = stones[i]
run_sum = 0

for j in range(i + 1, n):
new_run = run_sum+stones[j]
dp[j] = max(new_run - dp[j], run_sum+v - dp[j - 1])
run_sum = new_run
return dp[n - 1]

stones = [6,4,2,5,3]
print(solve(stones))

Input

[6,4,2,5,3]


Output

8
Published on 06-Oct-2021 11:10:16

Advertisements