trappedRainwater

mail@pastecode.io avatar
unknown
java
8 months ago
966 B
2
Indexable
Never
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static int trappedRainwater(int height[]){
        int n=height.length;
        //calc left max boundary -array
        int leftMax[]=new int[n];
        leftMax[0]=height[0];
        for(int i=1;i<n;i++){
            leftMax[i]=Math.max(height[i],leftMax[i-1]);
        }
        //calc right max boundary -array
        int rightMax[]=new int[n];
        rightMax[n-1]=height[n-1];
        for(int i=height.length-2;i>=0;i--){
            rightMax[i]=Math.max(height[i],rightMax[i+1]);
        }
        int trappedWater=0;
        for(int i=0;i<height.length;i++){
           int waterLevel =Math.min(rightMax[i],leftMax[i]);
           trappedWater+=waterLevel-height[i];
        }
        return trappedWater;
    }
	public static void main (String[] args)
	{
		// your code goes here
		int height[]={4,2,0,6,3,2,5};
		System.out.println(trappedRainwater(height));
		

	}
}