Skip to content

Commit

Permalink
ADD: trapping rain water problem
Browse files Browse the repository at this point in the history
  • Loading branch information
InclinedScorpio committed Sep 30, 2024
1 parent 8972fe9 commit 3cabba0
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions XDaysChallenge/90DaysChallenge/Day7/trapping_rain_water.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// https://leetcode.com/problems/trapping-rain-water/

/**
* Keeping leftMax and rightMax as a preprocessing step
* Focus on current index, and check if it can store water
*/
class Solution {
public:
int trap(vector<int>& height) {

vector<int> left(height.size(), 0);
vector<int> right(height.size(), 0);
int leftMax=0, rightMax=0;

for(int i=0, j=height.size()-1;i<height.size();i++, j--) {
left[i] = leftMax;
leftMax = max(leftMax, height[i]);
right[j] = rightMax;
rightMax = max(rightMax, height[j]);
}

int waterStored=0;
for(int i=0;i<height.size();i++) {
int maxCurrHeight = min(left[i], right[i]);
if(maxCurrHeight>height[i]) {
waterStored += (maxCurrHeight - height[i]);
}
}
return waterStored;
}
};

0 comments on commit 3cabba0

Please sign in to comment.