Skip to content

Commit

Permalink
Create 042.Trapping-Rain-Water_stack.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored May 24, 2020
1 parent 7eff1ea commit 52df7f4
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Others/042.Trapping-Rain-Water/042.Trapping-Rain-Water_stack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public:
int trap(vector<int>& height)
{
stack<int>Stack;
int ret = 0;

for (int i=0; i<height.size(); i++)
{
while (!Stack.empty() && height[Stack.top()] < height[i])
{
int base = height[Stack.top()];
Stack.pop();
if (Stack.empty()) continue;
int h = min(height[Stack.top()], height[i]) - base;
int w = i - Stack.top()-1;
ret += h*w;
}
Stack.push(i);
}
return ret;
}
};

0 comments on commit 52df7f4

Please sign in to comment.