Find the year with the most number of people alive in Python

后端 未结 9 2092
梦谈多话
梦谈多话 2020-12-14 20:48

Given a list of people with their birth and end years (all between 1900 and 2000), find the year with the most number of people alive.

Here

9条回答
  •  天涯浪人
    2020-12-14 21:30

    I would go like this:

    • Sort persons by birth year (unborn list)
    • Starting from the first born
      • Put that person in the alive list
      • Using an insertion sort by date of death (the list stays sorted, so use a binary search)
      • Until you reach a person that was not born that year
    • Then, starting from the person in the alive list that dies first, remove it from the list.
    • Put the size of the alive list in a dict
    • Increment the year
    • Loop until the unborn and alive lists are empty

    Complexity should be around O((m + n) * log(m)) (each year is considered only once, and each person only twice, multiplied by the insertion cost in the alive list)

    Implementation

    from bisect import insort
    
    def most_populated(population, single=True):
        years = dict()
        unborn = sorted(population, key=lambda x: -x[0])
        alive = []
        dead = []
        for year in range(unborn[-1][0], max(population, key=lambda x: x[1])[1] + 1):
            while unborn and unborn[-1][0] == year:
                insort(alive, -unborn.pop()[1])
            while alive and alive[-1] == -(year - 1):
                dead.append(-alive.pop())
            years[year] = len(alive)
        return max(years, key=years.get) if single else \
               [key for key, val in years.iteritems() if val == max(years.values())]
    

提交回复
热议问题