Bag of Tokens in C++


Suppose we have an initial power P, an initial score of 0 points, and one bag of tokens. Now each token can be used at most once, there is a value token[i], and has potentially two ways to use it, these are as follows −

  • If we have at least token[i] power, then we may play the token face up, losing token[i] power, and gaining 1 point.

  • Otherwise when we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.

We have to find the largest number of points that we can have after playing any number of tokens.

So if the input is like tokens = [100,200,300,400] and P = 200, then the output will be 2.

To solve this, we will follow these steps −

  • n := size of array v, ret := 0

  • sort the v array

  • set i := 0 and j := n – 1, curr :=

  • while i <= j and x >= v[i]

    • while i <= j and x >= v[i]

      • decrease x by v[i], increase curr and i by 1

    • ret := max of curr and ret

    • while j >= i and curr is not 0 and x < v[i]

      • increase x by v[j], decrease curr and j by 1

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int bagOfTokensScore(vector<int>& v, int x) {
      int n = v.size();
      int ret = 0;
      sort(v.begin(), v.end());
      int i = 0;
      int j = n - 1;
      int curr = 0;
      while(i <= j && x >= v[i]){
         while(i <= j && x >= v[i]){
            x -= v[i];
            curr++;
            i++;
         }
         ret = max(curr, ret);
         while(j >= i && curr && x < v[i]){
            curr--;
            x += v[j];
            j--;
         }
      }
      return ret;
   }
};
main(){
   vector<int> v1 = {100,200,300,400};
   Solution ob;
   cout << (ob.bagOfTokensScore(v1, 200));
}

Input

[100,200,300,400]
200

Output

2

Updated on: 30-Apr-2020

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements