Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

Problem Link

Trapping Rain Water - LeetCode

Reference Video

https://www.youtube.com/watch?v=C8UjlJZsHBw

Code

// Time Complexity : O(n)
// Space Complexity : O(n)

class Solution {
public:
    int trap(vector<int>& height) {
        
        int n = height.size();
        int res = 0;
        
        if(n==0)
            return res;
        
        vector<int> leftmax(n);
        
        leftmax[0] = height[0];
        
        for(int i=1;i<n;i++)
        {
            leftmax[i] = max(leftmax[i-1],height[i]);
        }
        
        vector<int> rightmax(n);
        
        rightmax[n-1] = height[n-1];
        
        for(int i=n-2;i>=0;i--)
        {
            rightmax[i] = max(rightmax[i+1],height[i]);
        }
        
        
        
        for(int i=1;i<n-1;i++)
        {
            int minht = min(leftmax[i],rightmax[i]);
            res+=(minht-height[i]);
        }
        
        return res;
    }
};

Space Optimized Approach

// Time Complexity : O(n)
// Space Complexity : O(1)

class Solution {
public:
    int trap(vector<int>& height) {
        
        int n = height.size();
        int res = 0;
        
        if(n==0)
            return res;
        
        int left = 0;
        int right = n-1;
        int maxleft = height[0];
        int maxright = height[n-1];
        
        while(left<=right)
        {
            if(maxleft<maxright)
            {
                if(height[left]>maxleft)// water can't be stored at this height
                    maxleft = height[left];
                else
                    res+=maxleft-height[left];
                
                left++;
            }
            
            else
            {
                if(height[right]>maxright)// water can't be stored at this height
                    maxright = height[right];
                else
                    res+=maxright-height[right];
                
                right--;
                    
            }
        }
        
        return res;
    }
};