Link: https://leetcode.com/problems/predict-the-winner/
Solution:
Topics: DP, Stone game
Intuition
This is essentially the same problem as Stone game. I was pleased to have solved this easily given how much I struggled in the past on these “optimal play” DP patterns.
Since this is basically the same problem as Stone game, Ill just show my first solution and then how I optimized it…and why the two lead to the same result.
Implementation (player variable)
The above solution works fine, but it is not the most clever way to do it. In the above, I am manually propagating player
variable to keep track of who’s turn it is and then using some switching logic to control the arithmetic.
What can be done instead is to control this process through arithmetic alone. This requires a deeper faith in top-down recursion… but the reward is some damn clean code.
Implementation (faith in recursion)
Review 1
For some reason I thought there was a math trick here because the constraints were suspicious, but I did eventually rule that out and proceeded to solve this cleanly with DP! Nice problem.