Skip to content

Commit

Permalink
Add problem 2256: Minimum Average Difference
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jul 4, 2024
1 parent 1859805 commit ddfffac
Show file tree
Hide file tree
Showing 3 changed files with 74 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 @@ -1581,6 +1581,7 @@ pub mod problem_2243_calculate_digit_sum_of_a_string;
pub mod problem_2244_minimum_rounds_to_complete_all_tasks;
pub mod problem_2248_intersection_of_multiple_arrays;
pub mod problem_2255_count_prefixes_of_a_given_string;
pub mod problem_2256_minimum_average_difference;
pub mod problem_2259_remove_digit_from_number_to_maximize_result;
pub mod problem_2260_minimum_consecutive_cards_to_pick_up;
pub mod problem_2262_total_appeal_of_a_string;
Expand Down
55 changes: 55 additions & 0 deletions src/problem_2256_minimum_average_difference/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
pub struct Solution;

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

impl Solution {
pub fn minimum_average_difference(nums: Vec<i32>) -> i32 {
let mut left_sum = 0;
let mut left_count = 0;
let mut right_sum = nums.iter().fold(0_u64, |sum, &x| sum + u64::from(x as u32));
let mut right_count = nums.len() as u64;
let mut min_diff = u64::MAX;
let mut min_diff_index = 0;

for num in nums {
let num = u64::from(num as u32);

left_count += 1;
right_count -= 1;
left_sum += num;
right_sum -= num;

let left_average = left_sum / left_count;
let right_average = if right_count == 0 { 0 } else { right_sum / right_count };

let diff = left_average.abs_diff(right_average);

if diff < min_diff {
min_diff = diff;
min_diff_index = left_count;

if diff == 0 {
break;
}
}
}

(min_diff_index - 1) as _
}
}

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

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

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

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

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

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

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

0 comments on commit ddfffac

Please sign in to comment.