diff --git a/src/lib.rs b/src/lib.rs index e77e8cfb..496037fb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1500,6 +1500,7 @@ pub mod problem_2044_count_number_of_maximum_bitwise_or_subsets; pub mod problem_2047_number_of_valid_words_in_a_sentence; pub mod problem_2049_count_nodes_with_the_highest_score; pub mod problem_2053_kth_distinct_string_in_an_array; +pub mod problem_2054_two_best_non_overlapping_events; pub mod problem_2055_plates_between_candles; pub mod problem_2057_smallest_index_with_equal_value; pub mod problem_2058_find_the_minimum_and_maximum_number_of_nodes_between_critical_points; diff --git a/src/problem_2054_two_best_non_overlapping_events/iterative.rs b/src/problem_2054_two_best_non_overlapping_events/iterative.rs new file mode 100644 index 00000000..c67a44dc --- /dev/null +++ b/src/problem_2054_two_best_non_overlapping_events/iterative.rs @@ -0,0 +1,62 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::convert::TryInto; + +impl Solution { + fn parse_event(event: &[i32]) -> &[i32; 3] { + event.try_into().ok().unwrap() + } + + pub fn max_two_events(events: Vec>) -> i32 { + const PROBE: u64 = 1 << 32; + + let mut events_2 = Vec::with_capacity(events.len() * 2); + + events_2.extend(events.iter().map(|event| { + let &[start, _, value] = Self::parse_event(event); + + (u64::from(start as u32) << 33) | u64::from(value as u32) + })); + + events_2.extend(events.iter().map(|event| { + let &[_, end, value] = Self::parse_event(event); + + (u64::from(end as u32) << 33) | PROBE | u64::from(value as u32) + })); + + drop(events); + + events_2.sort_unstable(); + + let mut result = 0; + let mut max = 0; + + for state in events_2 { + if state & PROBE == 0 { + result = result.max(max + state as u32); + } else { + max = max.max(state as u32); + } + } + + result as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn max_two_events(events: Vec>) -> i32 { + Self::max_two_events(events) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2054_two_best_non_overlapping_events/mod.rs b/src/problem_2054_two_best_non_overlapping_events/mod.rs new file mode 100644 index 00000000..6cb72452 --- /dev/null +++ b/src/problem_2054_two_best_non_overlapping_events/mod.rs @@ -0,0 +1,22 @@ +pub mod iterative; + +pub trait Solution { + fn max_two_events(events: Vec>) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[[1, 3, 2], [4, 5, 2], [2, 4, 3]] as &[_], 4), + (&[[1, 3, 2], [4, 5, 2], [1, 5, 5]], 5), + (&[[1, 5, 3], [1, 5, 1], [6, 6, 5]], 8), + ]; + + for (events, expected) in test_cases { + assert_eq!(S::max_two_events(events.iter().map(Vec::from).collect()), expected); + } + } +}