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.
1 #include<stdio.h> 2 3 int trap( int* height, int heightSize ){ 4 5 int left = 0; 6 int right = heightSize - 1; 7 int middle = 0; 8 int water = 0; 9 10 while( left < right ){ 11 12 if( height[left] < height[right]){ 13 middle = middle > height[left] ? middle : height[left]; 14 water = water + middle - height[left]; 15 left ++; 16 }else{ 17 middle = middle > height[right] ? middle : height[right]; 18 water = water + middle - height[right]; 19 right --; 20 } 21 } 22 printf("Water is %d\n", water); 23 return water; 24 } 25 26 int main(){ 27 int height[] = {0,1,0,2,1,0,1,3,2,1,2,1}; 28 int heightSize = 12; 29 trap( height, heightSize ); 30 return 0; 31 }
时间: 2024-10-23 20:40:02