101 Logo
onenoughtone

Code Implementation

Token Strategy Game Implementation

Below is the implementation of the token strategy game:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Greedy Approach with Sorting
* Time Complexity: O(n log n) - Sorting the tokens takes O(n log n) time
* Space Complexity: O(1) - We only use a constant amount of extra space
*
* @param {number[]} tokens - Array of token values
* @param {number} power - Initial power
* @return {number} - Maximum score achievable
*/
function bagOfTokensScore(tokens, power) {
// Sort tokens in ascending order
tokens.sort((a, b) => a - b);
let left = 0;
let right = tokens.length - 1;
let score = 0;
let maxScore = 0;
while (left <= right) {
// If we can play the smallest token face up
if (power >= tokens[left]) {
power -= tokens[left];
left++;
score++;
maxScore = Math.max(maxScore, score);
}
// If we can play the largest token face down
else if (score > 0) {
power += tokens[right];
right--;
score--;
}
// If we can't make any move
else {
break;
}
}
return maxScore;
}

Step-by-Step Explanation

Let's break down the implementation:

  1. 1. Understand the Problem: First, understand that we need to maximize our score by strategically playing tokens either face up or face down.
  2. 2. Sort the Tokens: Sort the tokens in ascending order to easily access the smallest and largest tokens.
  3. 3. Use Two Pointers: Use two pointers to track the smallest and largest tokens that haven't been played yet.
  4. 4. Implement the Greedy Strategy: Play the smallest tokens face up and the largest tokens face down, always choosing the move that maximizes our score.
  5. 5. Track the Maximum Score: Keep track of the maximum score achieved during the game, as we might temporarily decrease our score to gain more power.
  6. 6. Handle Edge Cases: Consider edge cases such as empty token arrays or when we don't have enough power to play any token.
  7. 7. Test the Solution: Verify the solution with the provided examples and additional test cases.
ProblemSolutionCode
101 Logo
onenoughtone