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.
class Solution {
public:
int findMax(int A[], int n) {
int max = A[];
int max_index = ;
for(int i = ; i < n; i++) {
if (A[i] > max){
max = A[i];
max_index = i;
}
}
return max_index;
} int trap(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n <= )
return ; int max_index = findMax(A, n);
int water = ; int i = max_index;
while(i >= ){
int left_max_index = findMax(A, i - + );
//calculate water between left_max and max
for(int j = left_max_index + ; j < i; j ++)
water += A[left_max_index] - A[j]; i = left_max_index;
} i = max_index;
while( n - (i + ) >= ){
int right_max_index = findMax(A + i + , n - i - ) + i + ;
//calculate water between right_max and max
for(int j = i + ; j < right_max_index; j++)
water += A[right_max_index] - A[j]; i = right_max_index;
} return water;
}
};