LeetCode-11 Container With Most Water

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

This question is hard to depict at first, the way of trappign water is like a bar graph.


                              |    ***         |                 
               |              |    ***         |                    
               |    |    |    |    ***    |    |                    
          |    |    |    |    |    ***    |    |                     
          |    |    |    |    |    ***    |    |              |       
     |    |    |    |    |    |    ***    |    |              |       
     |    |    |    |    |    |    ***    |    |              |    |   
     |    |    |    |    |    |    ***    |    |    |         |    |   
     |    |    |    |    |    |    ***    |    |    |    |    |    |

I found a very detailed explanation on github:
Source

The basic idea is to use 2 pointers search, starting with the borders.
If the inner bar is shorter than the max already found (keep track of leftMax and rightMax), there is no need to calc it, just move on.

class Solution {
    public int maxArea(int[] height) {
        int lowMax = 0, highMax=height.length-1;
        int lo=lowMax, hi=highMax;
        int res = 0;
        while(lo<hi){
            highMax=height[hi];
            lowMax=height[lo];
            res = Math.max(res,(hi-lo)*Math.min(height[hi], height[lo]));

            if(height[lo]>height[hi]){
                while(hi>-1&&height[hi]<=highMax)  hi--;
            }else{
                while(lo<height.length&&height[lo]<=lowMax) lo++;
            }
        }

        return res;
    }
}