Skip to content

Instantly share code, notes, and snippets.

@dashsaurabh
Created January 20, 2020 11:11
Show Gist options
  • Save dashsaurabh/97b4b41c87085c0d81a132ae3f91e36b to your computer and use it in GitHub Desktop.
Save dashsaurabh/97b4b41c87085c0d81a132ae3f91e36b to your computer and use it in GitHub Desktop.
Solution for Trapping RainWater Problem
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