Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Trapping Rain Water

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.

Brute force

PrefixSum Optimized

2-pointer

Code

class Solution {
public:
    int trap(vector<int>& height)
    {
        int n = height.size();
        int left = 0, right = n - 1;
        int res = 0;
        int maxLeft = 0, maxRight = 0;

        while (left <= right) {
            if (height[left] <= height[right]) { // update max left
                if (height[left] > maxLeft) maxLeft = height[left];
                else res += maxLeft - height[left];
                left++;
            } else { // update max right
                if (height[right] > maxRight) maxRight = height[right];
                else res += maxRight - height[right];
                right--;
            }
        }
        return res;
    }
};