Sponsored
Sponsored
This approach involves using a two-pointer technique to process the tokens. By sorting the tokens array, we aim to utilize the smallest possible tokens first to maximize score when power allows, and then balance power by utilizing score if achievable.
Start by sorting the tokens array. Maintain two pointers: one at the start to play face-up when you have enough power, and the other at the end to play face-down when a score can be sacrificed to gain more power. Keep track of the current score and maximum score achieved. This greedy approach helps in maximizing score by trying to play as many tokens face-up as possible while being able to trade score for power when needed.
The time complexity is O(n log n)
due to sorting the tokens
array. The space complexity is O(1)
as no additional space besides variables is used.
1using System;
2
3public class Solution {
4 public int BagOfTokensScore(int[] tokens, int power) {
5 Array.Sort(tokens);
6 int left = 0, right = tokens.Length - 1;
7 int score = 0, maxScore = 0;
8 while (left <= right) {
9 if (power >= tokens[left]) {
10 power -= tokens[left++];
11 score++;
12 maxScore = Math.Max(maxScore, score);
13 } else if (score > 0) {
14 power += tokens[right--];
15 score--;
16 } else {
17 break;
18 }
19 }
20 return maxScore;
21 }
22
23 public static void Main(string[] args) {
24 Solution solution = new Solution();
25 int[] tokens = new int[] {100, 200, 300, 400};
26 int power = 200;
27 Console.WriteLine("Maximum Score: " + solution.BagOfTokensScore(tokens, power));
28 }
29}
This C# solution similarly employs sorting and a two-pointer strategy. The Array.Sort
method is used for sorting. As power and score are updated, the maximum possible score is calculated and returned.
In the dynamic programming approach, we consider decisions at each token in terms of playing face-up or face-down, and store results for subproblems to optimize the score obtained.
The dynamic programming table, dp[i][j]
, keeps track of the maximum score achievable with the first i
tokens and with j
power. For each token, either spend or gain power while adjusting the score, and calculate the best possible outcome for each state.
The time complexity is O(n * m)
where n
is the number of tokens and m
is the initial power range explored. The space complexity is also O(n * m)
due to the DP table usage.
This C implementation uses a DP table to track the best scores possible at each state. As the array updates for each token processed, it compares the outcomes of playing the token face-up or face-down. The final answer is at dp[tokensSize][power]
, representing the maximum score achievable for the given number of tokens and initial power.