Trapping Rain Water [LeetCode]

Problem Description: http://oj.leetcode.com/problems/trapping-rain-water/

Basic idea: Get the index of max number of the array, then split the array at that point. Find the left max num, calcaute the water trapped between left max num and the max num. Go left recursively until meeting the start of the array. Do the same thing to the right part.

 1 class Solution {
 2 public:
 3     int findMax(int A[], int n) {
 4         int max = A[0];
 5         int max_index = 0;
 6         for(int i = 0; i < n; i++) {
 7             if (A[i] > max){
 8                 max = A[i];
 9                 max_index = i;
10             }
11         }
12         return max_index;
13     }
14     
15     int trap(int A[], int n) {
16         // Note: The Solution object is instantiated only once and is reused by each test case.
17         if(n <= 2)
18             return 0;
19 
20         int max_index = findMax(A, n);
21         int water = 0;
22       
23         int i = max_index;
24         while(i >= 2){
25             int left_max_index = findMax(A, i - 1 + 1);
26             //calculate water between left_max and max
27             for(int j = left_max_index + 1; j < i; j ++)
28                 water += A[left_max_index] - A[j];
29             
30             i = left_max_index;
31         }
32         
33         i = max_index;
34         while( n - (i + 1) >= 2){
35             int right_max_index = findMax(A + i + 1, n - i - 1) + i + 1;
36             //calculate water between right_max and max
37             for(int j = i + 1; j < right_max_index; j++)
38                 water += A[right_max_index] - A[j];
39             
40             i = right_max_index;
41         }
42         
43         return water;
44     }
45 };

posted @ 2013-10-21 13:59  假日笛声  阅读(463)  评论(0编辑  收藏  举报