Program to find winner of array removal game in Python

PythonServer Side ProgrammingProgramming

Suppose Amal and Bimal are playing a game where they have one array A with some numbers.The game rules are as follows

  • Bimal will start always
  • In each turn one player deletes the maximum element from the array and all other elements present at right of the deleted element will also be deleted.
  • They play alternatively
  • The player who removes all remaining elements, he will win the game.

So, if the input is like nums = [5,2,6,3,4], then the output will be Amal because at first Bimal will remove [6,3,4] so array will be [5,2], then Amal will remove all, so he will be the winner.

To solve this, we will follow these steps −

  • maximum := -1
  • count := 0
  • for each a in nums, do
    • if a > maximum is non-zero, then
      • count := count + 1
      • maximum := a
  • if count mod 2 is same as 0, then
    • return "Amal"
  • return "Bimal"

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   maximum = -1
   count = 0
   for a in nums:
      if a > maximum:
         count += 1
         maximum = a
   if count % 2 == 0:
      return "Amal"
   return "Bimal"

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

Input

[5,2,6,3,4]

Output

Amal
raja
Updated on 23-Oct-2021 07:00:23

Advertisements