Skip to content

Commit f5fd263

Browse files
committed
Trapping rain water file added to array folder with complexities and explanation
1 parent 2fb620b commit f5fd263

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Arrays/trappingrainwater.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Given an array of numbers which are heights to the container, we need to find upto what maximum value water can be filled in this vessel
2+
// of different heights.
3+
// Time complexity - O(n)
4+
//Space complexity - O(1)
5+
#include<bits/stdc++.h>
6+
using namespace std;
7+
8+
int main(){
9+
int arr[]={1,8,6,2,5,4,8,3,7};
10+
int l=0,n=sizeof(arr)/sizeof(int),r=n-1;
11+
int max_area=0,h,a,b;
12+
13+
while(l<r){
14+
h=min(arr[l],arr[r]);
15+
b=r-l;
16+
a=h*b;
17+
max_area=max(a,max_area);
18+
if(arr[l]<=arr[r]){
19+
l++;
20+
}
21+
else{
22+
r--;
23+
}
24+
}
25+
cout<<"Maximum water that can be trapped is : "<<max_area;
26+
return 0;
27+
28+
}

0 commit comments

Comments
 (0)