Skip to content

Commit

Permalink
Add problem 2012: Sum of Beauty in the Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 20, 2023
1 parent f01099f commit 49652e8
Show file tree
Hide file tree
Showing 3 changed files with 77 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 @@ -1392,6 +1392,7 @@ pub mod problem_2000_reverse_prefix_of_word;
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;

#[cfg(test)]
mod test_utilities;
58 changes: 58 additions & 0 deletions src/problem_2012_sum_of_beauty_in_the_array/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
pub struct Solution;

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

impl Solution {
pub fn sum_of_beauties(nums: Vec<i32>) -> i32 {
let iter_1 = nums.iter().copied();
let mut iter_2 = iter_1.clone();

iter_2.next();

let mut iter_3 = iter_2.clone();

iter_3.next();

// Calculate right maxes.

let mut right_mins = vec![0; nums.len() - 2];
let mut right_min = i32::MAX;

for (target, num) in right_mins.iter_mut().zip(iter_3.clone()).rev() {
right_min = right_min.min(num);
*target = right_min;
}

let mut result = 0;

let mut left_max = i32::MIN;

for (((left, middle), right), right_min) in iter_1.zip(iter_2).zip(iter_3).zip(right_mins) {
left_max = left_max.max(left);

if left_max < middle && middle < right_min {
result += 2;
} else if left < middle && middle < right {
result += 1;
}
}

result
}
}

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

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

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

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

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

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

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

0 comments on commit 49652e8

Please sign in to comment.