Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 630e0ff

Browse files
trapping rainwater
1 parent 8bbeb01 commit 630e0ff

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎Arrays/TrappingRainwater.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
int trap(vector<int>& height)
7+
{
8+
int n = height.size();
9+
if (n == 0 || n == 1 || n == 2)
10+
return 0;
11+
12+
vector<int> leftMax(n, 0);
13+
vector<int> rightMax(n, 0);
14+
15+
leftMax[0] = height[0];
16+
rightMax[n - 1] = height[n - 1];
17+
18+
for (int i = 1; i < n; i++)
19+
leftMax[i] = max(leftMax[i - 1], height[i]);
20+
21+
for (int i = n - 2; i >= 0; i--)
22+
rightMax[i] = max(rightMax[i + 1], height[i]);
23+
24+
int ans = 0;
25+
for (int i = 1; i <= n - 2; i++) {
26+
ans += max((min(leftMax[i - 1], rightMax[i + 1]) - height[i]), 0);
27+
}
28+
return ans;
29+
}
30+
31+
int main() {
32+
vector<int> array;
33+
34+
int number;
35+
36+
while (cin >> number) {
37+
array.push_back(number);
38+
}
39+
40+
cout << trap(array) << endl;
41+
42+
return 0;
43+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /