Recursive Solution Java


  • 0
    N
    public int trap(int[] height) {
    
        if(height.length<=2) return 0;
        int max = 0;
        int maxvalue = 0;
        int sec = 0;
        int secv = 0;
        int water = 0;
        for(int i=0;i<height.length;i++){
            if(height[i]>=maxvalue) {
                maxvalue = height[i];
                max=i;
    
            }
        }
        for(int j=0;j<height.length;j++){
            if(height[j]>=secv&&j!=max) {
                sec=j;
                secv = height[j];
            }
        }
        if(max!=0&&max!=height.length-1){
            return trap(Arrays.copyOfRange(height,0,max+1))+trap(Arrays.copyOfRange(height,max,height.length));
       }
        else if(sec!=0&&sec!=height.length-1){
            return trap(Arrays.copyOfRange(height,0,sec+1))+trap(Arrays.copyOfRange(height,sec,height.length));
        }
        else{
          //  if(height.length<=2) return 0;
            for(int k=1;k<height.length-1;k++){
                water += (height[sec]-height[k]);
            }
            return water;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.