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
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.