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
Bob's Game in Python
Suppose we have a friend named Bob, and he is playing a game with himself. He gives himself a list of numbers called nums. Now in each turn, Bob selects two elements of the list and replaces them with one positive integer with the same sum as the numbers he selected. Bob declares victory when all of the numbers in the array are even. We have to find the minimum number of turns required by Bob so he can declare victory. If there is no such solution, then return -1.
So, if the input is like [2, 3, 4, 9, 7, 13], then the output will be 2 as he can take 3, 9 then replace with 12, then take 7, 13 and replace with 20.
Logic
The key insight is that only odd numbers prevent victory. When we add two odd numbers, we get an even number. When we add two even numbers, we get an even number. But adding an odd and even number gives an odd number.
To solve this, we will follow these steps ?
odd_nums:= a list containing only odd elements fromnums-
if the count of odd numbers is even, then
return
(count of odd numbers) / 2
otherwise return
-1
Example
class Solution:
def solve(self, nums):
odd_nums = [x for x in nums if x % 2 == 1]
if len(odd_nums) % 2 == 0:
return len(odd_nums) // 2
return -1
ob = Solution()
print(ob.solve([2, 3, 4, 9, 7, 13]))
The output of the above code is ?
2
How It Works
In the example [2, 3, 4, 9, 7, 13], we have four odd numbers: [3, 9, 7, 13]. Since we have an even count of odd numbers (4), we can pair them up: (3, 9) and (7, 13). Each pair requires one turn to combine into an even number, so we need 4 / 2 = 2 turns.
Edge Cases
ob = Solution() # All even numbers - already victory print(ob.solve([2, 4, 6, 8])) # Odd count of odd numbers - impossible print(ob.solve([1, 3, 5])) # Single odd number - impossible print(ob.solve([1, 2, 4]))
The output of the above code is ?
0 -1 -1
Conclusion
Bob can achieve victory only when there's an even count of odd numbers in the list. The minimum turns required equals half the count of odd numbers, as each turn combines two odd numbers into one even number.
