
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Tokens in C
- C/C++ Tokens?
- What are tokens in Java?
- What are tokens in C#?
- Explain C tokens in C Language
- What are the tokens in C ?
- Substitute tokens in a String in Java
- Tokens vs Identifiers vs Keywords in C++
- What are the C Tokens?
- C program to print string tokens
- Crypto Primer: Currencies, Commodities and Tokens
- C program to detect tokens in a C program
- What do you mean by C++ Tokens?
- Crypto Tokens: Everything you need to know
- Who is the suicide bag of the cell?
