Living People
Last updated
Last updated
16.10 Living People: 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.
Brute force: Go through each year, and increment a count to see how many people are alive in said year. To do this, we have have a vector<pair<int>>
that maps year:count
. Iterate through the original list starting with the first year, and iterate through the remainder of the list by simply checking if said year is within the boundary of the current year. This will take a nest for loop, O(n^2).
Optimized:
If we sort both the deaths and years we can create the following visualization.
Green represents the amount of births accumulated over a period of time. And red represents the accumulation of deaths of time. The difference of births and deaths (outlined in blue) indicates to us the amount of people who are alive of said current year.
So algorithm now:
Sort births and deaths.
Fill in the gaps between the years (optional). When we have one birth, this means +1 accumulation on births. If nothing happens is said year, then the accumulation stays the same.