package leetcode;

/**
 * https://leetcode.com/problems/trapping-rain-water/
 */
public class Problem42 {
    public int trap(int[] height) {
        boolean zero = true;
        int prev = 0;
        int prevIdx = 0;
        for (int i = 0; i < height.length; i++) {
            if (height[i] == 0 && zero) {
                continue;
            }
            zero = false;
            if (prev >= height[i]) {
                prevIdx = i;
                prev = height[i];
                if (prev > 0) {
                    // to be continued
                }
            }
        }
        return 0;
    }
    
    public static void main(String[] args) {
        Problem42 prob = new Problem42();
        System.out.println(prob.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})); // 6
    }
}

@@ -147,122 +147,146 @@
     
-boolean zero = true;%0A        int prev = 0;%0A        int prevIdx = 0;%0A        for (int i = 0; i %3C height.length; i++
+int left = 0;%0A        int right = height.length - 1;%0A        boolean leftTurn = false;%0A        int result = 0;%0A        while (left %3C right
 ) %7B%0A
@@ -312,23 +312,30 @@
 ght%5B
-i%5D == 0 && zero
+left%5D %3C= height%5Bright%5D
 ) %7B%0A
@@ -350,22 +350,29 @@
         
-contin
+leftTurn = tr
 ue;%0A    
@@ -372,32 +372,39 @@
 e;%0A            %7D
+ else %7B
 %0A            zer
@@ -404,12 +404,20 @@
     
-zero
+    leftTurn
  = f
@@ -438,96 +438,224 @@
     
-if (prev %3E= height%5Bi%5D) %7B%0A                prevIdx = i;%0A                prev = height%5Bi%5D;%0A
+%7D%0A            if (leftTurn) %7B%0A                int i = left + 1;%0A                int area = 0;%0A                while (height%5Bi%5D %3C height%5Bleft%5D && i %3C right) %7B%0A                    area += height%5Bleft%5D - height%5Bi%5D;%0A    
     
@@ -671,28 +671,30 @@
    i
-f (prev %3E 0) %7B%0A
+++;%0A          
      
+ %7D%0A
     
@@ -708,26 +708,24 @@
     
-// to be continued
+ result += area;
 %0A   
@@ -729,33 +729,41 @@
                 
-%7D
+left = i;
 %0A            %7D%0A 
@@ -752,32 +752,39 @@
 i;%0A            %7D
+ else %7B
 %0A        %7D%0A     
@@ -780,32 +780,69 @@
     
-%7D%0A        return
+        int i = right - 1;%0A                int area =
  0;%0A    
 %7D%0A  
@@ -841,197 +841,276 @@
     
-%7D%0A
+    
     
-%0A
     
-public static void main(String%5B%5D args) %7B%0A        Problem42 prob = new Problem42();%0A        System.out.println(prob.trap(new int%5B%5D%7B0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1%7D)); // 6
+while (height%5Bi%5D %3C height%5Bright%5D && i %3E left) %7B%0A                    area += height%5Bright%5D - height%5Bi%5D;%0A                    i--;%0A                %7D%0A                result += area;%0A                right = i;%0A            %7D%0A        %7D%0A        return result;
 %0A    %7D%0A%7D
 %0A
@@ -1108,9 +1108,8 @@
 %0A    %7D%0A%7D
-%0A

Solve problem 42