Created
November 9, 2018 22:39
-
-
Save hsaputra/ec320d493bcc18ea67d2d4efd8dbdd6b to your computer and use it in GitHub Desktop.
Trapping Rain Water - https://leetcode.com/explore/interview/card/facebook/5/round-1-phone-interview/295/
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
class Solution { | |
public int trap(int[] height) { | |
int count = 0; | |
int left = 0; | |
int right = height.length - 1; | |
int maxLeft = 0; | |
int maxRight = 0; | |
while (left < right) { | |
if (height[left] < height[right]) { | |
if (height[left] > maxLeft) { | |
maxLeft = height[left]; | |
} else { | |
// We have trap | |
count += maxLeft - height[left]; | |
} | |
left++; | |
} else { | |
if (height[right] > maxRight) { | |
maxRight = height[right]; | |
} else { | |
// we have a trap | |
count += maxRight - height[right]; | |
} | |
right--; | |
} | |
} | |
return count; | |
} | |
} |
Author
hsaputra
commented
Nov 9, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment