From 4061ff562b129de9073feba171038905e7965f5b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 4 Mar 2024 11:21:15 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB948.=20Bag=20of=20Tokens?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/bag-of-tokens.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 rs/bag-of-tokens.rs diff --git a/rs/bag-of-tokens.rs b/rs/bag-of-tokens.rs new file mode 100644 index 0000000..17bc310 --- /dev/null +++ b/rs/bag-of-tokens.rs @@ -0,0 +1,56 @@ +struct Solution {} +impl Solution { + pub fn bag_of_tokens_score(mut tokens: Vec, mut power: i32) -> i32 { + if tokens.is_empty() { + return 0; + } + + tokens.sort_unstable(); + + let mut i = 0; + let mut j = tokens.len() - 1; + + let mut score = 0; + while i <= j { + if power >= tokens[i] { + // can trade score for power + power -= tokens[i]; + score += 1; + i += 1; + } else if i < j && score > 0 { + // can trade power for score + score -= 1; + power += tokens[j]; + j -= 1; + } else { + // no further action is possible + break; + } + } + + score + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!(Solution::bag_of_tokens_score(vec![100], 50), 0); + } + + #[test] + fn example_2() { + assert_eq!(Solution::bag_of_tokens_score(vec![200, 100], 150), 1); + } + + #[test] + fn example_3() { + assert_eq!( + Solution::bag_of_tokens_score(vec![100, 200, 300, 400], 200), + 2 + ); + } +}