Skip to content

Commit

Permalink
Add problem 1964: Find the Longest Valid Obstacle Course at Each Posi…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
EFanZh committed Aug 19, 2024
1 parent d9c8d23 commit d7f99fa
Show file tree
Hide file tree
Showing 3 changed files with 68 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 @@ -1458,6 +1458,7 @@ pub mod problem_1959_minimum_total_space_wasted_with_k_resizing_operations;
pub mod problem_1961_check_if_string_is_a_prefix_of_array;
pub mod problem_1962_remove_stones_to_minimize_the_total;
pub mod problem_1963_minimum_number_of_swaps_to_make_the_string_balanced;
pub mod problem_1964_find_the_longest_valid_obstacle_course_at_each_position;
pub mod problem_1967_number_of_strings_that_appear_as_substrings_in_word;
pub mod problem_1968_array_with_elements_not_equal_to_average_of_neighbors;
pub mod problem_1969_minimum_non_zero_product_of_the_array_elements;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
pub mod stack;

pub trait Solution {
fn longest_obstacle_course_at_each_position(obstacles: Vec<i32>) -> Vec<i32>;
}

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

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

for (obstacles, expected) in test_cases {
assert_eq!(
S::longest_obstacle_course_at_each_position(obstacles.to_vec()),
expected,
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
pub struct Solution;

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

impl Solution {
pub fn longest_obstacle_course_at_each_position(obstacles: Vec<i32>) -> Vec<i32> {
let mut obstacles = obstacles;
let mut lengths = Vec::with_capacity(obstacles.len());

for height in &mut obstacles {
let height_u32 = *height as u32;
let i = lengths.partition_point(|&x| x <= height_u32);

if let Some(value) = lengths.get_mut(i) {
*value = height_u32;
} else {
lengths.push(height_u32);
}

*height = i as i32 + 1;
}

obstacles
}
}

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

impl super::Solution for Solution {
fn longest_obstacle_course_at_each_position(obstacles: Vec<i32>) -> Vec<i32> {
Self::longest_obstacle_course_at_each_position(obstacles)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit d7f99fa

Please sign in to comment.