Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trapping rain water problem using c++(Optimised) #567

Merged
merged 15 commits into from
Jul 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Arrays/trappingrainwater.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// 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
// of different heights.
// Time complexity - O(n)
//Space complexity - O(1)
#include<bits/stdc++.h>
using namespace std;

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

while(l<r){
h=min(arr[l],arr[r]); //choosing the minimum of both heights -left and right side
b=r-l; //base = right height index - left
a=h*b;
max_area=max(a,max_area); //idea to maximize the area to trap more water
if(arr[l]<=arr[r]){
l++; //if right ride height is greater move left pointer to choose max of heights
}
else{
r--; //else move right pointer to choose next max height
}
}
cout<<"Maximum water that can be trapped is : "<<max_area;
return 0;

}