Trapping Rain Water (in C++)
Please add this new file for the issue that I have raised for issue #1055pull/1060/head
parent
ec8bdb7c84
commit
136e5a4f02
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue