Package g0901_1000.s0948_bag_of_tokens
Class Solution
java.lang.Object
g0901_1000.s0948_bag_of_tokens.Solution
948 - Bag of Tokens.<p>Medium</p>
<p>You have an initial <strong>power</strong> of <code>power</code>, an initial <strong>score</strong> of <code>0</code>, and a bag of <code>tokens</code> where <code>tokens[i]</code> is the value of the <code>i<sup>th</sup></code> token (0-indexed).</p>
<p>Your goal is to maximize your total <strong>score</strong> by potentially playing each token in one of two ways:</p>
<ul>
<li>If your current <strong>power</strong> is at least <code>tokens[i]</code>, you may play the <code>i<sup>th</sup></code> token face up, losing <code>tokens[i]</code> <strong>power</strong> and gaining <code>1</code> <strong>score</strong>.</li>
<li>If your current <strong>score</strong> is at least <code>1</code>, you may play the <code>i<sup>th</sup></code> token face down, gaining <code>tokens[i]</code> <strong>power</strong> and losing <code>1</code> <strong>score</strong>.</li>
</ul>
<p>Each token may be played <strong>at most</strong> once and <strong>in any order</strong>. You do <strong>not</strong> have to play all the tokens.</p>
<p>Return <em>the largest possible <strong>score</strong> you can achieve after playing any number of tokens</em>.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> tokens = [100], power = 50</p>
<p><strong>Output:</strong> 0</p>
<p><strong>Explanation:</strong> Playing the only token in the bag is impossible because you either have too little power or too little score.</p>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> tokens = [100,200], power = 150</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong> Play the 0<sup>th</sup> token (100) face up, your power becomes 50 and score becomes 1.</p>
<p>There is no need to play the 1<sup>st</sup> token since you cannot play it face up to add to your score.</p>
<p><strong>Example 3:</strong></p>
<p><strong>Input:</strong> tokens = [100,200,300,400], power = 200</p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong> Play the tokens in this order to get a score of 2:</p>
<ol>
<li>Play the 0<sup>th</sup> token (100) face up, your power becomes 100 and score becomes 1.</li>
<li>Play the 3<sup>rd</sup> token (400) face down, your power becomes 500 and score becomes 0.</li>
<li>Play the 1<sup>st</sup> token (200) face up, your power becomes 300 and score becomes 1.</li>
<li>Play the 2<sup>nd</sup> token (300) face up, your power becomes 0 and score becomes 2.</li>
</ol>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= tokens.length <= 1000</code></li>
<li><code>0 <= tokens[i], power < 10<sup>4</sup></code></li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
bagOfTokensScore
public int bagOfTokensScore(int[] tokens, int power)
-