Water collected between towers

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

    You can traverse first from left to right, and calculate the water accumulated for the cases where there is a smaller building on the left and a larger one on the right. You would have to subtract the area of the buildings that are in between these two buildings and are smaller than the left one.

    Similar would be the case for right to left.

    Here is the code for left to right. I have uploaded this problem on leetcode online judge using this approach.

    I find this approach much more intuitive than the standard solution which is present everywhere (calculating the largest building on the right and the left for each i ).

    int sum=0, finalAns=0;
        idx=0;
        while(a[idx]==0 && idx < n)
            idx++;
        for(int i=idx+1;i

    The time complexity of this approach is O(n), as you are traversing the array two time linearly. Space complexity would be O(1).

提交回复
热议问题