Water collected between towers

后端 未结 26 1105
无人共我
无人共我 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
    2020-12-22 17:31

    An alternative algorithm in the style of Euclid, which I consider more elegant than all this scanning is:

    Set the two tallest towers as the left and right tower. The amount of water contained between these towers is obvious.

    Take the next tallest tower and add it. It must be either between the end towers, or not. If it is between the end towers it displaces an amount of water equal to the towers volume (thanks to Archimedes for this hint). If it outside the end towers it becomes a new end tower and the amount of additional water contained is obvious.

    Repeat for the next tallest tower until all towers are added.

    I've posted code to achieve this (in a modern Euclidean idiom) here: http://www.rosettacode.org/wiki/Water_collected_between_towers#F.23

提交回复
热议问题