Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.81 KB | None | 0 0
  1. //Runtime: 1 ms, faster than 98.11% of Java online submissions for Trapping Rain Water.
  2. //Memory Usage: 37.4 MB, less than 98.63% of Java online submissions for Trapping Rain Water.
  3. class Solution {
  4.   public int trap(int[] height) {
  5.     int volume = 0;
  6.     if(height == null || height.length == 0) return volume;
  7.    
  8.     int left = 0, leftMax = 0;
  9.     int right = height.length-1, rightMax = 0;
  10.    
  11.     while(right > left){
  12.       leftMax = Math.max(leftMax, height[left]);
  13.       rightMax = Math.max(rightMax, height[right]);
  14.       if(leftMax < rightMax){
  15.         int col = leftMax - height[left];
  16.         if(col > 0)  volume += col;    
  17.         left++;
  18.       }else{
  19.         int col = rightMax - height[right];
  20.         if(col > 0) volume += col;
  21.         right--;
  22.       }
  23.     }
  24.     return volume;
  25.   }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement