diff --git a/src/lib.rs b/src/lib.rs index 211ac327..18bd6181 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1393,6 +1393,7 @@ pub mod problem_2006_count_number_of_pairs_with_absolute_difference_k; pub mod problem_2007_find_original_array_from_doubled_array; pub mod problem_2011_final_value_of_variable_after_performing_operations; pub mod problem_2012_sum_of_beauty_in_the_array; +pub mod problem_2016_maximum_difference_between_increasing_elements; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2016_maximum_difference_between_increasing_elements/iterative.rs b/src/problem_2016_maximum_difference_between_increasing_elements/iterative.rs new file mode 100644 index 00000000..11eadd27 --- /dev/null +++ b/src/problem_2016_maximum_difference_between_increasing_elements/iterative.rs @@ -0,0 +1,36 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn maximum_difference(nums: Vec) -> i32 { + let mut result = -1; + let mut min = i32::MAX; + + for num in nums { + min = min.min(num); + + if num > min { + result = result.max(num - min); + } + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn maximum_difference(nums: Vec) -> i32 { + Self::maximum_difference(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2016_maximum_difference_between_increasing_elements/mod.rs b/src/problem_2016_maximum_difference_between_increasing_elements/mod.rs new file mode 100644 index 00000000..35492d1b --- /dev/null +++ b/src/problem_2016_maximum_difference_between_increasing_elements/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn maximum_difference(nums: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[7, 1, 5, 4] as &[_], 4), (&[9, 4, 3, 2], -1), (&[1, 5, 2, 10], 9)]; + + for (nums, expected) in test_cases { + assert_eq!(S::maximum_difference(nums.to_vec()), expected); + } + } +}