Leetcode

Trapping Rain Water Problem LeetCode Java Solution

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

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
class Solution {
    public int trap(int[] height) {
        int arrLength = height.length;
        int total = 0;
        if(arrLength<=2) return total;
        int[] leftMaxArr = new int[arrLength];
        int[] rightMaxArr = new int[arrLength];
        
        leftMaxArr = leftMax(leftMaxArr, height);
        rightMaxArr = rightMax(rightMaxArr, height);
        
        for(int i=0; i<arrLength; i++){
            if(leftMaxArr[i]<=rightMaxArr[i] && leftMaxArr[i]>height[i]){
                total = total + (leftMaxArr[i]-height[i]);
            }else if(rightMaxArr[i]<leftMaxArr[i] && rightMaxArr[i]>height[i] ){
                total = total + (rightMaxArr[i]-height[i]);
            }
        }
        
        return total;
        
    }
    
    public int[] leftMax(int[] arr, int[] height){
        int max = height[0];
        for(int i =0;i<height.length;i++){
            if(max>height[i]){
                    arr[i] = max;
            }else{
                arr[i] = height[i];
                max = height[i];
            }
            
        }
        return arr;

    }
    
    public int[] rightMax(int[] arr, int[] height){
        int max = height[height.length-1];
        for(int i =height.length-1;i>=0;i--){
            if(max>height[i]){
                    arr[i] = max;
            }else{
                arr[i] = height[i];
                max = height[i];
            }  
        }
        return arr;
    }
}

Here is the video explanation

rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

10 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.