You are given a 2D integer array logs
where each logs[i] = [birthi, deathi]
indicates the birth and death years of the i-th
person.
The population of some year x
is the number of people alive during that year. The i-th
person is counted in the population of year x
if x
is in the inclusive range [birthi, deathi - 1]
. Note that the person is not counted in the death year.
Return the year with the maximum population.
logs
and how long can it be?
We will use a strategy involving a difference array to determine the population changes efficiently:
population_changes
, to track changes in population for each year.logs
and apply the changes to this array.population_changes
array.def maxPopulationYear(logs):
# Define the range based on typical constraints (assuming 1950 to 2050)
start_year = 1950
end_year = 2051
num_years = end_year - start_year
# Array to store population changes
population_changes = [0] * num_years
# Apply population changes at birth and just after death
for birth, death in logs:
population_changes[birth - start_year] += 1
if death < end_year:
population_changes[death - start_year] -= 1
# Use prefix sum to compute population for each year
max_population = 0
current_population = 0
max_year = start_year
for year in range(num_years):
current_population += population_changes[year]
if current_population > max_population:
max_population = current_population
max_year = start_year + year
return max_year
# Example usage
logs = [[1993,1999], [2000,2010], [1975,2005], [1970,1982], [1980,2040], [1950,1961]]
print(maxPopulationYear(logs)) # Output should be a year with maximum population
Thus, the overall time complexity is O(N + Y), which is efficient given that typically Y (number of years) is fixed and relatively small.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?