Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find winner of array removal game in Python
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 wins 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.
Game Strategy
The key insight is that players will always choose the leftmost maximum element from the remaining array. Each time a new maximum is encountered while scanning left to right, it represents a potential move. The number of such moves determines the winner.
Algorithm Steps
To solve this, we will follow these steps −
- maximum := -1
- count := 0
- for each element a in nums, do
- if a > maximum, then
- count := count + 1
- maximum := a
- if a > maximum, then
- 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(f"Input: {nums}")
print(f"Winner: {solve(nums)}")
Input: [5, 2, 6, 3, 4] Winner: Amal
How It Works
For the array [5,2,6,3,4], we scan left to right:
- 5 > -1, so count = 1 (Bimal's turn)
- 2 < 5, no increment
- 6 > 5, so count = 2 (Amal's turn)
- 3 < 6, no increment
- 4 < 6, no increment
Total moves = 2 (even), so Amal wins.
Additional Example
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"
# Test with different arrays
test_cases = [
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[3, 1, 4, 1, 5]
]
for nums in test_cases:
winner = solve(nums)
print(f"Array: {nums} ? Winner: {winner}")
Array: [1, 2, 3, 4, 5] ? Winner: Amal Array: [5, 4, 3, 2, 1] ? Winner: Bimal Array: [3, 1, 4, 1, 5] ? Winner: Amal
Conclusion
The solution counts the number of left-to-right maximums in the array. If this count is even, Amal wins; otherwise, Bimal wins. This approach has O(n) time complexity and O(1) space complexity.
