Leetcode dynamic planning Trapping Rain Water, leetcodetrapping
This article is senlie original, reproduced Please retain this address: http://blog.csdn.net/zhengsenlie
Trapping Rain Water Total Accepted: 14568 Total Submissions: 50810My Submissions
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]
, Return6
.
The above elevation map is represented by array [,]. in this case, 6 units of rain water (blue section) are being trapped. thanks Marcos for contributing this image!
There is an array A [I] that represents the height of n columns. Calculate the maximum amount of water saved between these columns.
Idea: Left and Right dp
Use an array left [I] to indicate the height of the highest column on the left of the column I
Use an array right [I] to indicate the height of the highest column on the right of the column I
1. left-to-right scan, left [I] = max (left [I-1], A [I-1])
2. right [I] = max (right [I + 1], A [I + 1])
3. the water saved on column I is min (left [I], right [I])-A [I], because left [I] is useless, you can use it to store this value.
Complexity: time O (n), Space O (n)
Related questions:
Candy
int trap(int A[], int n){if (n == 3) return 0;vector<int> 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 ;}