Created
March 31, 2022 17:17
-
-
Save ThomasHigginson/67791be9c2bc374814045b66bd00057b to your computer and use it in GitHub Desktop.
This file contains 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
# This is the Dynamic Programming Solution/Approach | |
# Find the tallest left and tallest right for each index, then solve for the | |
# water each position will add to the total. | |
def trap(self, height: List[int]) -> int: | |
maxLefts, maxRights = [0] * len(height), [0] * len(height) | |
# init values | |
maxLefts[0] = height[0] | |
maxRights[len(height)-1] = height[len(height)-1] | |
i, j = 1, len(height)-2 | |
while i < len(height): | |
maxLefts[i] = max(maxLefts[i-1], height[i]) # Check this height to max height to left | |
maxRights[j] = max(maxRights[j+1], height[j]) # Check this height to max height to right | |
i += 1 | |
j -= 1 | |
# Determine answer | |
ans = 0 | |
for i in range(0, len(height)): | |
ans += max(0, min(maxLefts[i], maxRights[i]) - height[i]) | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment