Let be the sum of all monkey counts. Exactly one floor is removed per turn, so there are turns. Let be the player who does not take the last turn.
At each turn of , an even number of floors remain, hence at least two. Therefore, can always remove a floor other than the lowest remaining floor. All monkeys on that floor move to another floor, and collects none. This guarantees a total of zero regardless of the opponent's actions. Zero is the smallest possible total, so this strategy is optimal.
All monkeys belong to one of the players when the game ends. Consequently, the player taking the last turn collects all monkeys. If is odd, Ishigami takes the last turn and the answer is ; otherwise it is . The formula also holds when .
Sum the values while reading them. The time complexity is and the extra space complexity is . Since , use signed 64-bit integers for the sum and output.
Solution written by GPT