题解 | #接雨水问题#
接雨水问题
http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
class Solution { public: /** * max water * @param arr int整型vector the array * @return long长整型 */ long long maxWater(vector<int>& arr) { // write code here if(arr.size()<=2) return 0; int p=0, min = 0; //int f; long long sum = 0; int q = arr.size()-1; while(p<q){ while((arr[p]<=arr[p+1])&& (p < arr.size()-2) ) p++; while((arr[q]<=arr[q-1]) && (q>2)) q--; if(p>=q) return sum; min = arr[p]>arr[q] ? arr[q]:arr[p]; while((q>=p) && (arr[q] <= min)) { sum += min -arr[q]; q--; } min = arr[p]>arr[q] ? arr[q]:arr[p]; while((p<=q) && (arr[p] <= min)) { sum += min - arr[p]; p++; } } return sum; } };