Skip to content
Open
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
44 changes: 44 additions & 0 deletions Interview/Trapping Rain Water.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public:
int trap(vector<int>& height) {
int prevMaxHeight, result = 0, curResult = 0, peakIndex;

prevMaxHeight = 0;

for(int i = 1; i < height.size(); i++)
{
if(height[i] < height[prevMaxHeight])
{
curResult += (height[prevMaxHeight] - height[i]);
}

else
{
result += curResult;
curResult = 0;
prevMaxHeight = i;
}
}

peakIndex = prevMaxHeight;
prevMaxHeight = height.size() - 1;
curResult = 0;

for(int i = height.size() - 2; i >= peakIndex; i--)
{
if(height[i] < height[prevMaxHeight])
{
curResult += (height[prevMaxHeight] - height[i]);
}

else
{
result += curResult;
curResult = 0;
prevMaxHeight = i;
}
}

return result;
}
};