# Program to find maximum population year using Python

Suppose we have a table with two columns (birth, death) where each row is representing the birth and death years of the ith person. The population of some year y is the number of people alive during y. The ith person is counted in year y's population when y is in the inclusive range [birth_i, death_i - 1]. (The person is not counted in the year that they die). So, we have to find the earliest year with the maximum population.

So, if the input is like

 Birth Death 1970 2010 1960 2020 1940 1970

then the output will be 2 because there is only one value that matches with target, that is nums, so i = 4. Now |4-2| = 2.

To solve this, we will follow these steps −

• d := A map, where if some key is not found, return 0

• res := a list with two items [2051, 0]

• for each year of birth YOB, and year of death YOD in matrix, do

• for year in range YOB to YOD, do

• d[year] := d[year] + 1

• if d[year] >= res, then

• if d[year] > res, then

• res := a list with two elements [year, d[year]]

• otherwise,

• res := a list with two elements [(minimum of year and res), res]

• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import defaultdict
def solve(matrix):
d = defaultdict(int)
res = [2051, 0]
for YOB, YOD in matrix:
for year in range(YOB, YOD):
d[year] += 1
if d[year] >= res:
if d[year] > res:
res = [year, d[year]]
else:
res = [min(year, res), res]
return res
matrix = [[1970,2010],[1960,2020],[1940,1970]]
print(solve(matrix))

## Input

[[1970,2010],[1960,2020],[1940,1970]]

## Output

1960