Bag of Tokens

You have an initial power of P, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed).

Your goal is to maximize your total score by potentially playing each token in one of two ways:

1. If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score.

2. If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score.

Each token may be played at most once and in any order. You do not have to play all the tokens.

Return the largest possible score you can achieve after playing any number of tokens.

Example:

Input: tokens = [100,200], P = 150
Output: 1
Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int bagOfTokensScore(vector<int&tokensint P)
{
    //sort the array
    sort(tokens.begin(), tokens.end());
    int maxScore = 0;
    int currScore = 0;
    int start = 0end = tokens.size() - 1;

    //apply two pointer
    while (start <= end)
    {
        if (P - tokens[start] >= 0)
        {
            P -= tokens[start];
            currScore += 1;
            maxScore = max(maxScorecurrScore);
            start += 1;
        }
        else if (currScore >= 1)
        {
            P += tokens[end];
            currScore -= 1;
            end -= 1;
        }
        else
        {
            break;
        }
    }

    return maxScore;
}

int main()
{
    vector<inttokens = {100200};
    int P = 150;

    cout << bagOfTokensScore(tokensP);

    return 0;
}


No comments:

Post a Comment