Trapping Rain Water

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], return 6.



思路:

对于每一个柱子,在于左右两边的柱子,容纳的面积是min(max_left,max_right) - hight.

1.从左向右遍历,对于每个柱子,找出左边最大值;

2.从右向左遍历,对于每个柱子,找出右边最大值;

3,.再扫描一遍,统计每个柱子的累计和。

class Solution{
public:
	int trap(int A[],int n)
	{
		int *max_left = new int[n];
		int *max_right= new int[n];

		//在一个循环里面,算出来每一个柱子左,右边的最大值。
		for(int i =1;i<n;i++)
		{
			max_left[i]=max(max_left[i-1],A[i-1]);
			max_right[n-1-i]=max(max_right[n-i],A[n-i]);
		}

		int sum = 0;
		for (int i=0;i<n;i++)
		{
			int height=min(max_left[i],max_right[i]);
			if (height>A[i])
			{
				sum += height - A[i];
			}
		}
		
		delete []max_left;
		delete []max_right;
		return sum;
	}
};


你可能感兴趣的:(Trapping Rain Water)