title: trapping rain water elevations is array
body: <p>I was going through this problem in one of exam paper and found one solution in answer book. I am not able to understand algorithm behind it. Can anyone explain me how this algorithm works?</p>
  
  <p>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.</p>
  
  <p>For example, Given the input</p>
  
  <pre><code>[0,1,0,2,1,0,1,3,2,1,2,1] 
  </code></pre>
  
  <p>the return value would be</p>
  
  <pre><code>6
  </code></pre>
  
  <p>Solution as per answer book is this</p>
  
  <pre><code>public class Solution {
      public int trap(int[] height) {
          if (height.length &lt;=2 )
              return 0;
          int h = 0, sum = 0, i = 0, j = height.length - 1;
          while(i &lt; j)
          {
              if ( height[i] &lt; height[j] )
              {
                  h = Math.max(h,height[i]);
                  sum += h - height[i];
                  i++;
              }
              else
              {   
                  h = Math.max(h,height[j]);
                  sum += h - height[j];
                  j--;
              }
          }
          return sum;
      }
  }
  </code></pre>
  
  <p>Thanks</p>