Code for Trapping Rain Water
This code is intentionally made very precise and concise by following Functional Programming principles. We do the following step by step to get the result:
- First we check the corner/simplest cases and return 0 if found.
- So our final result will be a
sumof something. sumof what?sumof minimum of two values calculated fromheights. We also need to subtractheights[i]from them.minof which two values? Values calculated from left-to-right at each index and right-to-left at each index.- So we can return all these with that one statement.
xxxxxxxxxx21
def totalRain(heights): if not heights or len(heights) <= 2: return 0 return sum( [min( max(heights[:i+1] or heights[:1]), max(heights[i:] or heights[-1:]) ) - heights[i] for i in range(len(heights)) ] )if __name__ == '__main__': # uncomment a different array to see the working on a different array # myArr = [0, 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1, 0, 0] # should be 6 # myArr = [0, 0, 1, 0, 2, 4, 4, 4, 2, 3, 1, 0, 2, 4, 3, 1, 0, 1] # should be 14 # myArr = [0, 0, 1, 2, 4, 4, 4, 3, 1, 0, 0, 0] # should be 0 myArr = [5, 1, 2, 4, 4, 4, 3, 1, 0, 0, 0] # should be 5 print(totalRain(myArr))OUTPUT
Results will appear here.