本文为senlie原创。转载请保留此地址:
Trapping Rain Water
Total Accepted: 14568 Total Submissions: 50810Given 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!
相关题目:
Candy
int trap(int A[], int n){ if (n == 3) return 0; vector left(n, 0), right(n, 0); for(int i = 1; i < n - 1; ++i) left[i] = max(left[i - 1], A[i - 1]); for(int i = n - 2; i > 0; --i) { right[i] = max(right[i + 1], A[i + 1]); left[i] = min(left[i], right[i]) - A[i]; } int sum = 0; for_each(left.begin() + 1, left.end() - 1, [&sum](int c){ if(c > 0) sum += c; }); return sum ;}