Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Basic logic:we will find water trapped onto every building by min(left_max,right_max)-arr[i];
- T.C : O(n),S.C O(1),one pass
- 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.
- 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
- so,
- Case 1: if left_max < right_max:
- *We will think to get water over the ith building.
- we need max of 0 to i-1 that we already have ie. left_max
- 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
- but even if some building height is greater than right_max still we will have min(left_max,right_max) = left_max
- because left_max is smaller than even current right_max.
- Case 2: if left_max>=right_max:
- *We will think to get water over jth building.
- If left_max is greater and right_max is smaller then we need only smaller one so we got the water height.
- */
- class Solution:
- def maxWater(self, arr):
- i = 1
- j = len(arr) - 2
- left_max = arr[0]
- right_max = arr[-1]
- ans = 0
- while i <= j:
- if left_max > right_max:
- ans += max(0, right_max - arr[j])
- right_max = max(right_max, arr[j])
- j -= 1
- else:
- ans += max(0, left_max - arr[i])
- left_max = max(left_max, arr[i])
- i += 1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement