Skip to content

Commit abcff23

Browse files
authored
Merge pull request #567 from vishvarana/master
Trapping rain water problem using c++(Optimised)
2 parents eaa02af + 82bc2a8 commit abcff23

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Arrays/trappingrainwater.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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}; //array of diff heights
10+
int l=0,n=sizeof(arr)/sizeof(int),r=n-1;
11+
int max_area=0,h,a,b;
12+
//2 pointers algorithm
13+
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
17+
a=h*b;
18+
max_area=max(a,max_area); //idea to maximize the area to trap more water
19+
if(arr[l]<=arr[r]){
20+
l++; //if right ride height is greater move left pointer to choose max of heights
21+
}
22+
else{
23+
r--; //else move right pointer to choose next max height
24+
}
25+
}
26+
cout<<"Maximum water that can be trapped is : "<<max_area;
27+
return 0;
28+
29+
}

0 commit comments

Comments
 (0)