Skip to content

Commit

Permalink
Add problem 1854: Maximum Population Year
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Sep 21, 2023
1 parent e48be3f commit 69f7de9
Show file tree
Hide file tree
Showing 3 changed files with 76 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 @@ -1422,6 +1422,7 @@ pub mod problem_1844_replace_all_digits_with_characters;
pub mod problem_1845_seat_reservation_manager;
pub mod problem_1846_maximum_element_after_decreasing_and_rearranging;
pub mod problem_1848_minimum_distance_to_the_target_element;
pub mod problem_1854_maximum_population_year;

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

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

use std::convert::TryInto;

impl Solution {
pub fn maximum_population(logs: Vec<Vec<i32>>) -> i32 {
const MIN_YEAR: usize = 1950;

let mut diffs = [0_i8; 101];

for log in logs {
let [birth, death]: [_; 2] = log.try_into().ok().unwrap();

diffs[birth as u32 as usize - MIN_YEAR] += 1;
diffs[death as u32 as usize - MIN_YEAR] -= 1;
}

let mut max_population = 0;
let mut max_population_year = 0;
let mut population = 0;

for (year, diff) in (MIN_YEAR..).zip(diffs) {
population += diff;

if population > max_population {
max_population = population;
max_population_year = year;
}
}

max_population_year as _
}
}

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

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

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

pub trait Solution {
fn maximum_population(logs: Vec<Vec<i32>>) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(&[[1993, 1999], [2000, 2010]] as &[_], 1993),
(&[[1950, 1961], [1960, 1971], [1970, 1981]], 1960),
];

for (logs, expected) in test_cases {
assert_eq!(
S::maximum_population(logs.iter().copied().map(Vec::from).collect()),
expected
);
}
}
}

0 comments on commit 69f7de9

Please sign in to comment.