Leetcode 42. 接雨水

维护每个位置的左侧最大值L{}和右侧最大值R{}
若R[i]>height[i]且L[i]>height[i],k位置积水,且积水量为min(R[i], L[i]) - height[i]

const int maxn = 100005;
class Solution {
public:
    int L[maxn], R[maxn];
    int trap(vector<int>& height) {
        for (int i = 1; i < height.size(); ++i)
            L[i] = max(L[i - 1], height[i - 1]);
        for (int i = (int)height.size() - 2; i >= 0; --i)
            R[i] = max(R[i + 1], height[i + 1]);
        long long ans = 0;
        for (int i = 1; i <= (int)height.size() - 2; ++i)
            if (height[i] < L[i] && height[i] < R[i]) ans += min(R[i], L[i]) - height[i];
        return ans;
    }
};

你可能感兴趣的:(LeetCode)