Water collected between towers

后端 未结 26 1134
无人共我
无人共我 2020-12-22 16:51

I recently came across an interview question asked by Amazon and I am not able to find an optimized algorithm to solve this question:

You are given an input array wh

26条回答
  •  悲&欢浪女
    2020-12-22 17:25

    I wrote this relying on some of the ideas above in this thread:

    def get_collected_rain(towers):
    
        length = len(towers)
        acummulated_water=[0]*length
        left_max=[0]*length
        right_max=[0]*length
    
        for n in range(0,length):
    
            #first left item
            if n!=0:
                left_max[n]=max(towers[:n])
    
            #first right item
            if n!=length-1:
                right_max[n]=max(towers[n+1:length])
    
            acummulated_water[n]=max(min(left_max[n], right_max[n]) - towers[n], 0)
    
        return sum(acummulated_water)
    

    Well ...

    > print(get_collected_rain([9,8,7,8,9,5,6]))

    > 5

提交回复
热议问题