Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2022
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. class Solution {
  2.     public int trap(int[] height) {
  3.         int ans = 0;
  4.         int left = 0;
  5.         int right = height.length-1;
  6.        
  7.         int leftMax = 0;
  8.         int rightMax = 0;
  9.         while(left < right) {
  10.             if(height[left] < height[right]) {
  11.                 if(height[left] >= leftMax) {
  12.                     leftMax = height[left];
  13.                 } else {
  14.                     ans += leftMax - height[left];
  15.                 }
  16.                 left += 1;
  17.             } else {
  18.                 if(height[right] >= rightMax) {
  19.                     rightMax = height[right];
  20.                 } else {
  21.                     ans += rightMax - height[right];
  22.                 }
  23.                 right -= 1;
  24.             }
  25.         }
  26.         return ans;
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement