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.
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!
Analysis:
Find the max height at i, then the trapped water at position j less than (at left of) i depends on its max height on the left of i; similarly, the trapped water at position j greater than (at the right of) i depends on its max height on the right of j. No extra space needed for the solution.
int trap(int A[], int n) {
int maxHeight = 0;
int maxHeightPos = 0;
for (int i=0; i maxHeight) {
maxHeight = A[i];
maxHeightPos = i;
}
}
int sum = 0;
int leftHeight = 0;
for (int i=0; i < maxHeightPos; i++)
{
sum += max (0, leftHeight - A[i]);
leftHeight = max (A[i], leftHeight);
}
int rightHeight = 0;
for (int i=n-1; i > maxHeightPos; i--)
{
sum += max (0, rightHeight - A[i]);
rightHeight = max (A[i], rightHeight);
}
return sum;
}
No comments:
Post a Comment