Trapping Rain Water (in C++)

Please add this new file for the issue that I have raised for issue #1055
pull/1060/head
Avimathu 2022-10-21 11:42:30 +05:30 committed by GitHub
parent ec8bdb7c84
commit 136e5a4f02
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,40 @@
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int trap(vector<int>& heights) {
if(heights.size()<=2){
return 0;
}
vector<int> leftToRight;
int maxHeight = heights[0];
for(int i = 0; i < heights.size(); i++){
maxHeight = max(maxHeight , heights[i]);
leftToRight.push_back(maxHeight - heights[i]);
}
vector<int> rightToLeft;
maxHeight = heights[heights.size() - 1];
for(int i = heights.size() - 1; i >= 0; i--){
maxHeight = max(maxHeight , heights[i]);
rightToLeft.push_back(maxHeight - heights[i]);
}
reverse(rightToLeft.begin() , rightToLeft.end());
int ans = 0;
for(int i = 0; i < heights.size(); i++){
ans += min(leftToRight[i] , rightToLeft[i]);
}
return ans;
}
int main(){
int n;
cin>>n;
vector<int> heights(n,0);
for(int i=0;i<n;i++){
cin>>heights[i];
}
int waterTrapped=trap(heights);
cout<<waterTrapped;
return 0;
}