Rain Trapping
public class RainTrapping{ public static int rainTrapping(int height[]){ int max=0; for(int i=0;i<height.length;i++){ for(int j=i+1;j<height.length;j++){ int length=Math.min(height[i],height[j]); int breadth=Math.abs(j-i); int area=length*breadth; max=Math.max(area,max); } } return max; } /*Here time complexity is o(n^2) */ public static int rainTrapped(int height[]){ int left=0; int right=height.length-1; int max=0; while(left<=right){ int length=Math.min(height[left],height[right]); int breadth=Math.abs(left-right); int area=length*breadth; max=Math.max(max,area); if(left<=right){ left++; } else{ right--; } } return max; } /*Here Time complexity is o(nlogn) */ public static void main(String[] args){ int height[]={1,8,2,3,8,4,5,1,7}; System.out.println(rainTrapping(height)); System.out.println(rainTrapped(height)); } }
Leave a Comment