This article is Senlie original, reprint please retain this address:Http://blog.csdn.net/zhengsenlie
Trapping Rain WaterTotal Accepted: 14568 Total Submissions: 50810 My Submissions
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the 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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
Test instructions: There is an array representing the height of n pillars a[i], calculating the maximum amount of water that can be saved by the slots between these columns
Idea: Left and right DP
Use an array of left[i] to indicate the height of the highest pillar on the left of the pillar I
Use an array of right[i] to indicate the height of the highest pillar to the right of the pillar I
1. Scan from left to right, left[i] = max (left[i-1], a[i-1])
2. Right-to-left scan, right[i] = max (right[i + 1], A[i + 1])
3. The water on the pillar I can save is min (Left[i], right[i])-a[i], because at this time left[i] is useless, it can be used to store this value.
Complexity: Time O (n), space O (n)
Related Topics:
Candy
Longest palindromic Substring
int trap (int a[], int n) {if (n = = 3) return 0;vector<int> Left (n, 0), right (n, 0), and 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] = m In (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;}
Leetcode Dynamic planning trapping Rain water