题解 | #接雨水问题#
接雨水问题
http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
static const auto io_sync_off = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams std::cin.tie(nullptr); return nullptr; }(); class Solution { public: long long maxWater(vector<int>& arr) { vector<int> temp; temp.assign(arr.begin(),arr.end()); reverse(temp.begin(), temp.end()); int left=0; int right = max_element(arr.begin(),arr.end())-arr.begin(); long long sum=0; for (int i=0;i<arr.size();i++){ if(arr[i]<min(arr[left],arr[right])){ sum+=min(arr[left],arr[right])-arr[i]; }else if(i==right){ left=right; right=max_element(temp.begin(), temp.end()-i-1)-temp.begin(); right=arr.size()-right-1; } else if(arr[left]<=arr[i]){ left=i; } } return sum; } };