DEV Community

Debesh P.
Debesh P.

Posted on

42. Trapping Rain Water | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/trapping-rain-water/


leetcode 42


Solution

class Solution {
    public int trap(int[] height) {
        int n = height.length;

        int left = 0;
        int right = n - 1;

        int left_max = 0;
        int right_max = 0;

        int ans = 0;

        while(left <= right) {
            if(left_max <= right_max) {
                left_max = Math.max(left_max, height[left]);
                ans += left_max - height[left];
                left++;
            }
            else {
                right_max = Math.max(right_max, height[right]);
                ans += right_max - height[right];
                right--;
            }
        }

        return ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)