Advertisement
CreateWithChirag

Trapping Rain Water

Feb 18th, 2023
827
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | Source Code | 0 0
  1. class Solution {
  2.     public int trap(int[] height) {
  3.        
  4.         // Lmax
  5.         int Lmax[] = new int[height.length];
  6.         Lmax[0] = height[0];
  7.         for(int i =1; i <Lmax.length;i++){
  8.             int temp = Math.max(height[i] , Lmax[i-1]);
  9.             Lmax[i] = temp;
  10.         }
  11.        
  12.         //Rmax
  13.         int Rmax[] = new int[height.length];
  14.         Rmax[height.length-1] = height[height.length-1];
  15.         for(int i = Rmax.length-2; i >=0;i--){
  16.             int temp = Math.max(height[i] , Rmax[i+1]);
  17.             Rmax[i] = temp;
  18.         }
  19.  
  20.         // formula
  21.         int water =0;
  22.         for(int i =0; i < height.length;i++){
  23.             water += Math.min(Lmax[i], Rmax[i]) - height[i];
  24.         }
  25.        
  26.         return water;
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement