# leetcode Trapping Rain Water

### Trapping Rain Water

Total Accepted: 2335 Total Submissions: 8464

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Find the highest, then from the start to the highest, then the last to the highest..

class Solution {
public:
int trap(int A[], int n) {
if (n <= 2)
return 0;
int i, maxElevation = A[0], maxIndex = 0, h = 0, res = 0;
for (i = 1; i < n; ++i)
if (A[i] > maxElevation) {
maxElevation = A[i];
maxIndex = i;
}
for (i = 0; i <= maxIndex - 1; ++i)
if (A[i] >= h)
h = A[i];
else
res += (h - A[i]);

h = 0;
for (i = n - 1; i >= maxIndex + 1; --i)
if (A[i] >= h)
h = A[i];
else
res += (h - A[i]);
return res;
}
};

#### LeetCode: 42. Trapping Rain Water

2017-03-31 11:53:18

#### 【leetcode】42. Trapping Rain Water

2015-11-12 20:16:44

#### leetcode.42. Trapping Rain Water

2016-05-09 22:28:27

#### LeetCode 42 - Trapping Rain Water

2016-03-03 12:36:21

#### LeetCode:Trapping Rain Water

2014-04-09 10:08:50

#### Trapping Rain Water -- LeetCode

2014-03-10 03:50:31

#### [leetcode] 407. Trapping Rain Water II 解题报告

2016-09-29 06:25:11

#### LeetCode42——Trapping Rain Water

2015-10-19 22:36:02

#### 【LeetCode】Trapping Rain Water解题报告

2014-12-08 15:19:23

#### [LeetCode]Trapping Rain Water,解题报告

2014-01-02 11:11:59