Skip to content

Commit 82bc2a8

Browse files
authored
Update trappingrainwater.cpp
1 parent b2f033b commit 82bc2a8

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

Arrays/trappingrainwater.cpp

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,24 @@
66
using namespace std;
77

88
int main(){
9-
int arr[]={1,8,6,2,5,4,8,3,7};
9+
int arr[]={1,8,6,2,5,4,8,3,7}; //array of diff heights
1010
int l=0,n=sizeof(arr)/sizeof(int),r=n-1;
1111
int max_area=0,h,a,b;
12+
//2 pointers algorithm
1213

13-
while(l<r){
14-
h=min(arr[l],arr[r]);
15-
b=r-l;
14+
while(l<r){
15+
h=min(arr[l],arr[r]); //choosing the minimum of both heights -left and right side
16+
b=r-l; //base = right height index - left
1617
a=h*b;
17-
max_area=max(a,max_area);
18+
max_area=max(a,max_area); //idea to maximize the area to trap more water
1819
if(arr[l]<=arr[r]){
19-
l++;
20+
l++; //if right ride height is greater move left pointer to choose max of heights
2021
}
2122
else{
22-
r--;
23+
r--; //else move right pointer to choose next max height
2324
}
2425
}
2526
cout<<"Maximum water that can be trapped is : "<<max_area;
2627
return 0;
2728

28-
}
29+
}

0 commit comments

Comments
 (0)