Maximum Population Year

easy difference array prefix sum

Problem

You are given a list of life spans, where logs[i] = [birth, death] for one person and every year lies in 1950..2050. A person is counted in the population of each year from their birth year up to, but not including, their death year. Return the earliest year that has the largest population.

Inputlogs = [[1993,1999],[1995,2008],[2000,2008],[1996,2005]]
Output1996
From 1996 to 1998 three people (born 1993, 1995 and 1996) are alive at once — the peak population of 3 — and 1996 is the earliest such year.

def maximum_population(logs):
    delta = [0] * 101                  # one slot per year 1950..2050
    for birth, death in logs:
        delta[birth - 1950] += 1       # alive from the birth year
        delta[death - 1950] -= 1       # not counted in the death year
    best_year, best_pop, running = 1950, 0, 0
    for i in range(101):
        running += delta[i]            # population of year 1950 + i
        if running > best_pop:
            best_pop = running
            best_year = 1950 + i
    return best_year
function maximumPopulation(logs) {
  const delta = new Array(101).fill(0); // one slot per year 1950..2050
  for (const log of logs) {
    delta[log[0] - 1950] += 1;          // alive from the birth year
    delta[log[1] - 1950] -= 1;          // not counted in the death year
  }
  let bestYear = 1950, bestPop = 0, running = 0;
  for (let i = 0; i < 101; i++) {
    running += delta[i];                // population of year 1950 + i
    if (running > bestPop) {
      bestPop = running;
      bestYear = 1950 + i;
    }
  }
  return bestYear;
}
int maximumPopulation(int[][] logs) {
    int[] delta = new int[101];        // one slot per year 1950..2050
    for (int[] log : logs) {
        delta[log[0] - 1950] += 1;     // alive from the birth year
        delta[log[1] - 1950] -= 1;     // not counted in the death year
    }
    int bestYear = 1950, bestPop = 0, running = 0;
    for (int i = 0; i < 101; i++) {
        running += delta[i];           // population of year 1950 + i
        if (running > bestPop) {
            bestPop = running;
            bestYear = 1950 + i;
        }
    }
    return bestYear;
}
int maximumPopulation(vector<vector<int>>& logs) {
    int delta[101] = {0};              // one slot per year 1950..2050
    for (auto& log : logs) {
        delta[log[0] - 1950] += 1;     // alive from the birth year
        delta[log[1] - 1950] -= 1;     // not counted in the death year
    }
    int bestYear = 1950, bestPop = 0, running = 0;
    for (int i = 0; i < 101; i++) {
        running += delta[i];           // population of year 1950 + i
        if (running > bestPop) {
            bestPop = running;
            bestYear = 1950 + i;
        }
    }
    return bestYear;
}
Time: O(n + Y), Y = 101 years Space: O(Y) = O(1)