Title Description:
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 .
Idea: Scan the columns from left to right to find the maximum height Hli to the left of the current column and the maximum height HRI to the right. If Hli>a[i] and hri>a[i], then the current column can hold the volume of water is min (Hli,hri)-a[i].
Code:
int solution::trap (int a[],int n) {int i,j; int count = 0; int * Left_height_array = (int *) malloc (sizeof (int) *n); int Left_height_max = 0; for (i = 0;i < n;i++) {left_height_array[i] = Left_height_max; if (A[i] > Left_height_max) Left_height_max = A[i]; } int * Right_height_array = (int*) malloc (sizeof (int) *n); int Right_height_max = 0; for (i = N-1;i >=0;i--) {right_height_array[i] = Right_height_max; if (A[i] > Right_height_max) Right_height_max = A[i]; } for (i = 1;i < n-1;i++) {int left_height = left_height_array[i]; int right_height = Right_height_array[i]; if (Left_height > A[i] && right_height > A[i]) {if (Left_height > Right_height) Count = Count + (Right_height-a[i]); else Count = Count + (Left_height-a[i]); }} return count;}
Leetcode:trapping Rain Water