Skip to content

Commit

Permalink
Add problem 0896: Monotonic Array
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Dec 4, 2024
1 parent d42186c commit fecac91
Show file tree
Hide file tree
Showing 3 changed files with 58 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 @@ -449,6 +449,7 @@ pub mod problem_0884_uncommon_words_from_two_sentences;
pub mod problem_0889_construct_binary_tree_from_preorder_and_postorder_traversal;
pub mod problem_0890_find_and_replace_pattern;
pub mod problem_0895_maximum_frequency_stack;
pub mod problem_0896_monotonic_array;
pub mod problem_0900_rle_iterator;
pub mod problem_0915_partition_array_into_disjoint_intervals;
pub mod problem_0916_word_subsets;
Expand Down
33 changes: 33 additions & 0 deletions src/problem_0896_monotonic_array/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
pub struct Solution;

impl Solution {
pub fn is_monotonic(nums: Vec<i32>) -> bool {
let mut prev = nums[0];
let mut increasing = None;
for &num in &nums[1..] {
match (num.cmp(&prev), increasing) {
(std::cmp::Ordering::Less, None) => increasing = Some(false),
(std::cmp::Ordering::Greater, None) => increasing = Some(true),
(std::cmp::Ordering::Less, Some(true))
| (std::cmp::Ordering::Greater, Some(false)) => return false,
_ => (),
};
prev = num;
}
true
}
}

impl super::Solution for Solution {
fn is_monotonic(nums: Vec<i32>) -> bool {
Self::is_monotonic(nums)
}
}

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

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

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

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

for (nums, expected) in test_cases {
assert_eq!(S::is_monotonic(nums.to_vec()), expected);
}
}
}

0 comments on commit fecac91

Please sign in to comment.