Last active
October 11, 2018 22:56
-
-
Save lienista/fe72ecf4b497427d4286e0cb04dbd3ac to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 42. Trapping Rain Water - Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
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
| const trap = (number) => { | |
| let len = number.length; | |
| if(!len) return 0; | |
| let result = 0; | |
| let maxLeft = []; | |
| maxLeft[0] = number[0]; | |
| let maxRight = []; | |
| maxRight[len-1] = number[len-1]; | |
| for(let i=1; i<len; i++) { | |
| maxLeft[i] = Math.max(number[i], maxLeft[i-1]); | |
| } | |
| for(let i=len-2; i>=0; i--){ | |
| maxRight[i] = Math.max(number[i], maxRight[i+1]); | |
| } | |
| for(let i=0; i<len; i++){ | |
| result += Math.min(maxLeft[i], maxRight[i]) - number[i]; | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment