Skip to content

Commit

Permalink
Add problem 2016: Maximum Difference Between Increasing Elements
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 21, 2023
1 parent 49652e8 commit 3b20c5a
Show file tree
Hide file tree
Showing 3 changed files with 55 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 @@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub struct Solution;

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

impl Solution {
pub fn maximum_difference(nums: Vec<i32>) -> 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>) -> i32 {
Self::maximum_difference(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn maximum_difference(nums: Vec<i32>) -> i32;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 3b20c5a

Please sign in to comment.