Program to find maximum score of brick removal game in Python


Suppose Amal and Bimal are playing a game. They have an array nums which determines n bricks with numbered on top of it. In this game, players can alternatively remove one, two or three bricks from the top, and the numbers marked on the removed bricks are added to the score of that player. If always Amal starts first, we have to find how much score Amal get secure at maximum.

So, if the input is like nums = [1,2,3,4,5], then the output will be 6 because, Amal can remove brick {1}, {1,2} or {1,2,3}, if Amal selects first two or three elements, then Bimal can take all and get maximum score, but if Amal selects 1 at first, Bimal can take at most {2,3,4} = 9 and Amal can take 5, so total score of Amal is 1+5 = 6.

To solve this, we will follow these steps

  • INF := 9999
  • n := size of nums
  • reverse the list nums
  • temp := an array of size n and fill with 0
  • total := an array of size n and fill with 0
  • for each index i, and value val in nums, do
    • total[i] := total[i-1] + val
  • temp[0] := nums[0]
  • temp[1] := temp[0]+nums[1]
  • temp[2] := temp[1]+nums[2]
  • for i in range 3 to n - 1, do
    • a := nums[i]
    • b := nums[i] + nums[i-1]
    • c := nums[i] + nums[i-1] + nums[i-2]
    • temp[i] := maximum of a, b, c
  • return temp[n-1]

Example

Let us see the following implementation to get better understanding −

INF = 99999
def solve(nums):
   n = len(nums)
   nums.reverse()
   temp = [0]*n
   total = [0]*n
   for i, val in enumerate(nums):
      total[i] = total[i-1] + val
   temp[0] = nums[0]
   temp[1] = temp[0]+nums[1]
   temp[2] = temp[1]+nums[2]
   for i in range(3, n):
      a = nums[i]
      b = nums[i] + nums[i-1]
      c = nums[i] + nums[i-1] + nums[i-2]
      temp[i] = max(a, b, c)
   return temp[n-1]

nums = [1,2,3,4,5]
print(solve(nums))

Input

[1,2,3,4,5]

Output

6

Updated on: 23-Oct-2021

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements