Computer >> Computer tutorials >  >> Programming >> Python

Program to find maximum number of coins we can get using Python


Suppose there are 3*n number of piles of coins present, and they are of varying size, three players are playing a game like −

  • In each step, player1 will select any 3 piles of coins.

  • Of his choice, Player2 will pick the pile with the maximum number of coins.

  • Player1 will pick the next pile with maximum number of coins.

  • Player3 will pick the last pile.

  • Repeat these steps until there are no more piles of coins.

Now if we have an array of integers called piles where piles[i] is the number of coins in the ith pile, then we have to find the maximum number of coins which Player1 can have.

So, if the input is like piles = [2,4,1,2,7,8], then the output will be 9 because at first we can select a triplet (2,7,8), then Player2 selects 8, Player1 selects 7 and the 2 is for Player3. Then again select triplet (1,2,4), then Player2 selects pile with coin 4, then Player1 selects 2 and remaining 1 for Player3. Currently Player1 has 7+2 = 9 coins, this is the maximum.

To solve this, we will follow these steps −

  • sort the list piles

  • ans := 0

  • while size of piles is not same as 0, do

    • ans := ans + second last element from piles

    • delete second last element from piles

    • delete last element from piles

    • delete first element from piles

  • return ans

Let us see the following implementation to get better understanding −

Example

def solve(piles):
   piles.sort()
   ans = 0
   while(len(piles)!=0):
      ans = ans + piles[-2]
      del piles[-2]
      del piles[-1]
      del piles[0]
   return ans
piles = [2,4,1,2,7,8]
print(solve(piles))

Input

[2,4,1,2,7,8]

Output

9