Problem Description
You are given an array of tokens and an initial power. By playing tokens face-up (if you have enough power) you can gain a score, or playing them face-down (if you have a score) you can regain some power. The goal is to maximize your score by choosing the optimal order to play these tokens.
Key Insights
- Sort the tokens to easily access the smallest and largest values.
- Use a two-pointer approach: one pointer starts at the beginning (small tokens for gaining score) and one at the end (large tokens for regaining power).
- Gain score by playing a low-value token (if enough power), and if you get stuck, use a high-value token to convert a score into additional power.
- Maintain the maximum score obtained during the process.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the tokens list. Space Complexity: O(1) if sorting is done in-place, otherwise O(n).
Solution
We can solve the problem using a greedy two-pointer strategy. First, sort the tokens so that the smallest token is at the beginning and the largest at the end. Initialize two pointers: left (to gain score) and right (to gain power by sacrificing score). Keep track of the current score and update the maximum score achieved. While there are tokens available (left pointer is less than or equal to right pointer), check if the current power is enough to play the token at the left pointer. If yes, play it face-up, increase the score, reduce the power, and move the left pointer to the right. If not and if you have at least one score, play the token at the right pointer face-down to regain power (at a cost of one score) and move the right pointer to the left. Continue until you cannot make any move, and return the maximum score recorded. The main trick is to use the largest unused token to regain power when needed and to always accumulate score when possible.