title :
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
code : OJ Test via runtime:91 ms
1 classSolution:2 #@param A, a list of integers3 #@return An integer4 defTrap (self, A):5 #Special Case6 ifLen (A) <3:7 return08 #Left most & right most9Length=Len (A)TenLeft_most = [0 forIinchrange (LENGTH)] OneRight_most = [0 forIinchrange (LENGTH)] ACurr_max =0 - forIinchRange (LENGTH): - ifA[i] >Curr_max: theCurr_max =A[i] -Left_most[i] =Curr_max -Curr_max =0 - forIinchRange (length-1,-1,-1): + ifA[i] >Curr_max: -Curr_max =A[i] +Right_most[i] =Curr_max A #Sum the trap atsum =0 - forIinchRange (LENGTH): -sum = sum + MAX (0,min (Left_most[i],right_most[i])-A[i]) - returnSum
Ideas :
Bottom line: How much water a position can put on, depending on the smallest of the left and right sides with this position position high.
Imagine the physical environment in which a location can hold water, ensuring that the position is in a low-lying position. How can we meet the conditions of the low-lying position? Both sides have to have a higher element than this position. What if we can guarantee that there are more elements on both left and right that are higher than this position? As long as the left and right sides of the maximum value of the smaller one than this position large can be.
Leetcode "trapping Rain water" python implementation