Advertisement
imashutosh51

Trapping Rain Water

Jul 31st, 2022 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 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.     def maxWater(self, arr):
  21.         i = 1
  22.         j = len(arr) - 2
  23.         left_max = arr[0]
  24.         right_max = arr[-1]
  25.         ans = 0
  26.        
  27.         while i <= j:
  28.             if left_max > right_max:
  29.                 ans += max(0, right_max - arr[j])
  30.                 right_max = max(right_max, arr[j])
  31.                 j -= 1
  32.             else:
  33.                 ans += max(0, left_max - arr[i])
  34.                 left_max = max(left_max, arr[i])
  35.                 i += 1
  36.        
  37.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement