Given a list of people with their birth and death years, implement a method to compute the year with the most number of people alive. You may assume that all people were born between 1900 and 2000 (inclusive). If a person was alive during any portion of that year, they should be included in that year's count. For example, Person (birth= 1908, death= 1909) is included in the counts for both 1908 and 1909.
If there are more than one years that have the most number of people alive, return the smallest one.
The problem is actually about performing addition and subtraction operations on a continuous interval, and then finding the maximum value. This can be solved using a difference array.
Since the year range in the problem is fixed, we can use an array of length $102$ to represent the population changes from 1900 to 2000. Each element in the array represents the population change in that year, with positive numbers indicating the number of births and negative numbers indicating the number of deaths.
We traverse the birth and death years of each person, and add one and subtract one from the corresponding year's population change, respectively. Then we traverse the difference array, and find the maximum value of the prefix sum of the difference array. The year corresponding to the maximum value is the answer.
The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the birth and death years, and $C$ is the range of years.
classSolution{funcmaxAliveYear(_birth:[Int],_death:[Int])->Int{letbase=1900vardelta=Array(repeating:0,count:102)// Array to hold the changesforiin0..<birth.count{letstart=birth[i]-baseletend=death[i]-basedelta[start]+=1ifend+1<delta.count{delta[end+1]-=1}}varmaxAlive=0,currentAlive=0,maxYear=0foryearin0..<delta.count{currentAlive+=delta[year]ifcurrentAlive>maxAlive{maxAlive=currentAlivemaxYear=year+base}}returnmaxYear}}