Posted on

Description

Submission

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.size() < 2) return 0;
        int max_index = 0;
        for(int i = 0; i < height.size(); ++i) {
            if(height[max_index] < height[i]) max_index = i;
        }
        int left = 0;
        int area = 0;
        for(int i = 0; i < max_index; ++i) {
            if(height[i] > height[left]) {
                left = i;
            } else {
                area += (height[left] - height[i]);
            }
        }
        int right = height.size() - 1;
        for(int i = height.size() - 1; i > max_index; --i) {
            if(height[i] > height[right]) {
                right = i;
            } else {
                area += (height[right] - height[i]);
            }
        }
        return area;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *