![]() |
VOOZH | about |
Given an array arr[] of N integers and two players A and B are playing a game where the players pick the element with the maximum digit sum in their turns. In the end, the player with the maximum sum of the picked elements wins the game. Assuming that player A always starts the game first and both the players play optimally, the task is to find the winner of the game.
Examples:
Input: arr[] = {12, 43, 25, 23, 30}
Output: B
A choses 43
B chooses 25
A chooses 23
B chooses 30
A chooses 12
A's score = 43 + 23 + 12 = 78
B's score = 25 + 30 = 55
Input: arr[] = {2, 1, 1, 2}
Output: Draw
Approach: Sort the array based on the digit sum values of the integers, if the digit sum of two integers is same then they will be compared based on their values, this is because the value will maximize the sum in the end. After the array has been sorted based on the custom comparator, player A will try to pick the elements starting from the greatest (greedily).
Below is the implementation of the above approach:
A
Time Complexity: O(n*log(n)*d) where n is the size of the array and d is the maximum number of digits in any number present in the array.
Auxiliary Space: O(1)