4 ms·
Here's a solution that takes O(P + R) time, where P is the number of people and R is the total range of birth years. First, notice that you don't really care w
by gaylemcd 11y ago
Here's a solution that takes O(P + R) time, where P is the number of people and R is the total range of birth years.
First, notice that you don't really care who died when. All that matters is someone died. People's birth and death years are fungible, in a sense. Each birth increases the population by one and each death increases the population by one.
Basically, you'll create an array where the value at each index represents how much the population changed in that year (steps 1 to 3). Then you can use that array to find the highest population (step 4).
1. Get the min birth year and the max birth year.
2. Create an array where the size is the above range. Set to all zeros. Each index will map to / represent a year in the range.
3. Loop through all the people. For each person, increment the index of their birth year and decrement their death year (or the following year, depending on whether or not they're counted as alive the entire year of their death)
4. Just loop through the array, tracking the running sum at each index. The biggest running sum will indicate the highest population.
There are some other good solutions depending on what assumptions you make about P and R's relative size.
- TheLoneWolfling 11y agoHmm... If you sort everyone's births and deaths you can just walk through the array keeping track of the number of people alive at each point and the maximum number of people alive at any point (and the year(s) thereof). O(P log P) (from the sort), no explicit dependance on R. Are there any other good solutions? I cannot imagine that there would be anything that's sublinear in P, so about the only other thing I could imagine would be something that is linear in P and sublinear in R.
- gaylemcd 11y agoYes, that's another good solution. You can't really compare O(P + R) and O(P log P). Of course, you could argue that P could grow a lot faster than R, so O(P + R) would be better. That's probably true in a "real world" sense, but not in a mathematical sense.