-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbag-of-tokens.rs
77 lines (75 loc) · 2.48 KB
/
bag-of-tokens.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// 948. Bag of Tokens
// 🟠 Medium
//
// https://leetcode.com/problems/bag-of-tokens/
//
// Tags: Array - Two Pointers - Greedy - Sorting
struct Solution;
impl Solution {
/// Sort the input, after that greedily iterate over the tokens checking the token at both ends
/// of the vector, if we have enough remaining power to play the token on the left, do it and
/// gain one point, otherwise play the token on the right and gain that much power. On each
/// loop, we check if there are remaining tokens and if our score has gone negative. Return the
/// maximum amount of points seen.
///
/// Time complexity: O(n*log(n)) - We need to sort the input, after that, O(n)
/// Space complexity: O(n) - Sorting the input vector and the local copy.
///
/// Runtime 1 ms Beats 100%
/// Memory 2.08 MB Beats 100%
pub fn bag_of_tokens_score(mut tokens: Vec<i32>, power: i32) -> i32 {
let n = tokens.len() as i32;
tokens.sort_unstable();
let mut power = power;
let mut points = 0;
let mut res = 0;
let (mut l, mut r) = (0, n - 1);
while l <= r && points >= 0 {
if tokens[l as usize] <= power {
points += 1;
power -= tokens[l as usize];
l += 1;
} else {
points -= 1;
power += tokens[r as usize];
r -= 1;
}
res = res.max(points);
}
res
}
}
// Tests.
fn main() {
let tests = [
(vec![100], 50, 0),
(vec![200, 100], 150, 1),
(vec![71, 55, 82], 54, 0),
(vec![100, 200, 300, 400], 200, 2),
];
println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len());
let mut success = 0;
for (i, t) in tests.iter().enumerate() {
let res = Solution::bag_of_tokens_score(t.0.clone(), t.1);
if res == t.2 {
success += 1;
println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i);
} else {
println!(
"\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m",
i, t.2, res
);
}
}
println!();
if success == tests.len() {
println!("\x1b[30;42m✔ All tests passed!\x1b[0m")
} else if success == 0 {
println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m")
} else {
println!(
"\x1b[31mx\x1b[95m {} tests failed!\x1b[0m",
tests.len() - success
)
}
}