Skip to content

Latest commit

 

History

History
25 lines (23 loc) · 588 Bytes

042.md

File metadata and controls

25 lines (23 loc) · 588 Bytes

42. Trapping Rain Water

Solution 1 (O(n))

class Solution {
public:
    int trap(vector<int>& height) {
        int left = 0, right = height.size() - 1;
        int ans = 0;
        while (left < right) {
            int t = min(height[left], height[right]);
            while (height[left] <= t && left < right) {
                ans += t - height[left];
                left++;
            }
            while (height[right] <= t && left < right) {
                ans += t - height[right];
                right--;
            }
        }
        return ans;
    }
};