Skip to content

Commit

Permalink
Add problem 2140: Solving Questions With Brainpower
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Feb 23, 2024
1 parent 1e044c3 commit 602f896
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,7 @@ pub mod problem_2129_capitalize_the_title;
pub mod problem_2130_maximum_twin_sum_of_a_linked_list;
pub mod problem_2134_minimum_swaps_to_group_all_1s_together_ii;
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
pub mod problem_2140_solving_questions_with_brainpower;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::convert::TryInto;

impl Solution {
pub fn most_points(questions: Vec<Vec<i32>>) -> i64 {
let mut cache = vec![0; questions.len()].into_boxed_slice();

for (i, question) in questions.into_iter().enumerate().rev() {
let [points, brainpower]: [_; 2] = question.try_into().ok().unwrap();
let score_if_skip = cache.get(i + 1).copied().unwrap_or(0);

let score_if_solve =
u64::from(points as u32) + cache.get(i + 1 + brainpower as u32 as usize).copied().unwrap_or(0);

cache[i] = score_if_skip.max(score_if_solve);
}

cache[0] as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn most_points(questions: Vec<Vec<i32>>) -> i64 {
Self::most_points(questions)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
21 changes: 21 additions & 0 deletions src/problem_2140_solving_questions_with_brainpower/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod dynamic_programming;

pub trait Solution {
fn most_points(questions: Vec<Vec<i32>>) -> i64;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(&[[3, 2], [4, 3], [4, 4], [2, 5]] as &[_], 5),
(&[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], 7),
];

for (questions, expected) in test_cases {
assert_eq!(S::most_points(questions.iter().map(Vec::from).collect()), expected);
}
}
}

0 comments on commit 602f896

Please sign in to comment.