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{
- // Function to find the trapped water between the blocks.
- public:
- long long trappingWater(int arr[], int n){
- long long int left_max=arr[0],right_max=arr[n-1];
- long long int i=1,j=n-2,ans=0;
- while(i<=j){
- if(left_max<right_max){
- if(arr[i]>left_max) left_max=arr[i]; //it's top can't hold water because left side has no boundary
- else{
- ans+=(left_max-arr[i]);
- }
- i++;
- }
- else{
- if(arr[j]>right_max) right_max=arr[j]; //it's top can't hold because right side has no boundary
- else{
- ans+=(right_max-arr[j]);
- }
- j--;
- }
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement