Skip to main content
Back to problems
#1854
Easy Algorithms

Maximum population year

Array Counting Prefix Sum
63.7% acceptance
Feb 25, 2026
1541
285
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Return the earliest year with the maximum population.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_population(logs: Vec<Vec<i32>>) -> i32 {
    let mut diff = [0i32; 101]; // years 1950..=2050
    for log in &logs {
      let b = (log[0] - 1950) as usize;
      let d = (log[1] - 1950) as usize;
      diff[b] += 1;
      if d <= 100 {
        diff[d] -= 1;
      }
    }
    let mut max_pop = 0;
    let mut cur = 0;
    let mut best_year = 1950;
    for (i, &d) in diff.iter().enumerate() {
      cur += d;
      if cur > max_pop {
        max_pop = cur;
        best_year = 1950 + i as i32;
      }
    }
    best_year
  }
}