Last active
June 18, 2020 11:00
-
-
Save manojnaidu619/543ac9390b701041ffb5995c0e312f8c to your computer and use it in GitHub Desktop.
Trapping rain water problem in O(n) time and O(1) space.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Problem here -> https://leetcode.com/problems/trapping-rain-water/ | |
height = [0,1,0,2,1,0,1,3,2,1,2,1] # Elevation map | |
lm, rm = 0, 0 | |
left, right = 0, len(height)-1 | |
water = 0 | |
while left<right: | |
if height[left]>lm: lm = height[left] | |
if height[right]>rm: rm = height[right] | |
if lm < rm: | |
water += max(0, lm-height[left]) | |
left+=1 | |
else: | |
water += max(0, rm-height[right]) | |
right-=1 | |
print(water) | |
# Time complexity = O(n) | |
# Space complexity = O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment