Given the life time of different elephants, find the period when maximum number of elephants lived

For each elephant, create two events: elephant born, elephant died. Sort the events by date. Now walk through the events and just keep a running count of how many elephants are alive; each time you reach a new maximum, record the starting date, and each time you go down from the maximum record the ending date.

This solution doesn't depend on the dates being integers.


If i were you at the interview i would create a std::array with maximum age of the elephant and then increment elements number for each elephant like:

[5,10] << increment all elements from index 5 to 10 in array.

Then i would sort and find where is the biggest number.

There is possibility to use std::map like map<int,int> ( 1st - period, 2nd - number of elephants). It will be sorted by default.

Im wondering if you know any better solution?

Tags:

C++