948. Bag of Tokens Medium

@problem@discussion
#Array#Two Pointers#Greedy#Sorting



1/**
2 * [948] Bag of Tokens
3 *
4 * You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the i^th token (0-indexed).
5 * Your goal is to maximize your total score by potentially playing each token in one of two ways:
6 * 
7 * 	If your current power is at least tokens[i], you may play the i^th token face up, losing tokens[i] power and gaining 1 score.
8 * 	If your current score is at least 1, you may play the i^th token face down, gaining tokens[i] power and losing 1 score.
9 * 
10 * Each token may be played at most once and in any order. You do not have to play all the tokens.
11 * Return the largest possible score you can achieve after playing any number of tokens.
12 *  
13 * Example 1:
14 * 
15 * Input: tokens = [100], power = 50
16 * Output: 0
17 * Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.
18 * 
19 * Example 2:
20 * 
21 * Input: tokens = [100,200], power = 150
22 * Output: 1
23 * Explanation: Play the 0^th token (100) face up, your power becomes 50 and score becomes 1.
24 * There is no need to play the 1^st token since you cannot play it face up to add to your score.
25 * 
26 * Example 3:
27 * 
28 * Input: tokens = [100,200,300,400], power = 200
29 * Output: 2
30 * Explanation: Play the tokens in this order to get a score of 2:
31 * 1. Play the 0^th token (100) face up, your power becomes 100 and score becomes 1.
32 * 2. Play the 3^rd token (400) face down, your power becomes 500 and score becomes 0.
33 * 3. Play the 1^st token (200) face up, your power becomes 300 and score becomes 1.
34 * 4. Play the 2^nd token (300) face up, your power becomes 0 and score becomes 2.
35 * 
36 *  
37 * Constraints:
38 * 
39 * 	0 <= tokens.length <= 1000
40 * 	0 <= tokens[i], power < 10^4
41 * 
42 */
43pub struct Solution {}
44
45// problem: https://leetcode.com/problems/bag-of-tokens/
46// discuss: https://leetcode.com/problems/bag-of-tokens/discuss/?currentPage=1&orderBy=most_votes&query=
47
48// submission codes start here
49
50impl Solution {
51    pub fn bag_of_tokens_score(tokens: Vec<i32>, power: i32) -> i32 {
52        0
53    }
54}
55
56// submission codes end
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_948() {
64    }
65}
66


Back
© 2025 bowen.ge All Rights Reserved.