Created
January 20, 2020 11:11
-
-
Save dashsaurabh/97b4b41c87085c0d81a132ae3f91e36b to your computer and use it in GitHub Desktop.
Solution for Trapping RainWater Problem
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
var trap = function(height) { | |
let left_max = []; | |
let right_max = []; | |
let rainWaterUnits = 0; | |
let n = height.length; | |
left_max[0] = height[0] | |
for(let i=1;i<n;i++) { | |
left_max[i] = Math.max(height[i], left_max[i-1]); | |
} | |
right_max[n-1] = height[n-1]; | |
for(let i = n-2; i>=0; i--) { | |
right_max[i] = Math.max(height[i], right_max[i+1]); | |
} | |
for(let i=0;i<height.length;i++) { | |
rainWaterUnits = rainWaterUnits + (Math.min(left_max[i], right_max[i]) - height[i]); | |
} | |
return rainWaterUnits; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment