Water collected between towers

后端 未结 26 1150
无人共我
无人共我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 17:20

    I have a solution that only requires a single traversal from left to right.

    def standing_water(heights):
    
        if len(heights) < 3:
            return 0
    
        i = 0   # index used to iterate from left to right
        w = 0   # accumulator for the total amount of water
    
        while i < len(heights) - 1:
    
            target = i + 1
            for j in range(i + 1, len(heights)):
    
                if heights[j] >= heights[i]:
                    target = j
                    break
    
                if heights[j] > heights[target]:
                    target = j
    
            if target == i:
                return w
    
            surface = min(heights[i], heights[target])
    
            i += 1
    
            while i < target:
                w += surface - heights[i]
                i += 1
    
        return w
    

提交回复
热议问题