Advertisement
imashutosh51

Trapping Rain Water

Jul 31st, 2022 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. /*
  2. Basic logic:we will find water trapped onto every building by min(left_max,right_max)-arr[i];
  3.  
  4. T.C : O(n),S.C O(1),one pass
  5. In our algo,left_max will store maximum of 0 to i-1 and right_max will store maximum of j+1 to n-1.
  6. using two pointer(i,j),so if we think about ith index,so we have left_max for 0 to i-1 and right_max from j+1 to n-1
  7. so,
  8. Case 1: if left_max < right_max:
  9.  *We will think to get water over the ith building.
  10.  we need max of 0 to i-1 that we already have ie. left_max
  11.  we need max of i+1 to n-1 but we have maxiumum of j+1 to n-1 only,not having maxiumum of i+1 to j
  12.  but even if some building height is greater than right_max still we will have min(left_max,right_max) = left_max
  13.  because left_max is smaller than even current right_max.
  14. Case 2: if left_max>=right_max:
  15.  *We will think to get water over jth building.
  16.  If left_max is greater and right_max is smaller then we need only smaller one so we got the water height.
  17. */
  18.  
  19. class Solution{
  20.  
  21.     // Function to find the trapped water between the blocks.
  22.     public:
  23.     long long trappingWater(int arr[], int n){
  24.         long long int left_max=arr[0],right_max=arr[n-1];
  25.         long long int i=1,j=n-2,ans=0;
  26.         while(i<=j){
  27.            if(left_max<right_max){
  28.                if(arr[i]>left_max) left_max=arr[i];  //it's top can't hold water because left side has no boundary
  29.                else{
  30.                    ans+=(left_max-arr[i]);
  31.                }
  32.                i++;
  33.            }  
  34.            else{
  35.                if(arr[j]>right_max)  right_max=arr[j];  //it's top can't hold because right side has no boundary
  36.                else{
  37.                    ans+=(right_max-arr[j]);
  38.                }
  39.                j--;
  40.            }
  41.         }
  42.         return ans;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement