Algorithm to solve find max no at a time

前端 未结 5 1115
半阙折子戏
半阙折子戏 2021-01-19 05:13

Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. Th

5条回答
  •  走了就别回头了
    2021-01-19 05:26

    Here a python scrypt

    n=5
    birthAndDeath = [-80000, -79950, 20, 70, 22, 60, 58, 65, 1950, 2004]
    birth = [] #date of birth of dinos 
    death = [] #date of death of dinos
    
    currentAliveDinos=0
    maxDinos=0
    dateLastBornForMax=0
    b = 0
    d = 0
    
    #we populate the both arrays for births and deaths
    for i in range(0,2*n,2):
        birth.append(birthAndDeath[i])
        death.append(birthAndDeath[i+1])
    
    #don't forget to sort arrays particuliary for death
    death.sort()
    birth.sort()
    print birth
    print death
    
    while b!=5 and d!=5:#there are still unborn dino
        if birth[b] < death[d]: # a dino born
            currentAliveDinos = currentAliveDinos + 1
            b = b + 1 
        else: # a dino died
            currentAliveDinos = currentAliveDinos - 1
            d = d + 1       
    
        if maxDinos < currentAliveDinos:
            maxDinos = currentAliveDinos
            dateLastBornForMax=birth[b-1]
    
        print currentAliveDinos
    
    print "max dinos = ", maxDinos, " and last dino born in ", dateLastBornForMax, " when max achieved"
    

提交回复
热议问题