Water collected between towers

后端 未结 26 1120
无人共我
无人共我 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

    Here's an efficient solution in Haskell

    rainfall :: [Int] -> Int
    rainfall xs = sum (zipWith (-) mins xs)
        where mins = zipWith min maxl maxr
              maxl = scanl1 max xs
              maxr = scanr1 max xs
    

    it uses the same two-pass scan algorithm mentioned in the other answers.

提交回复
热议问题