public int maxArea(int[] height) {
if (height.length == 0)
return 0;
int overAllMax = Integer.MIN_VALUE;
for (int i=0,j=height.length1;i<j;){
// calculate the current area;
int currentArea = Math.abs(ij) * Math.min(height[i],height[j]);
// if it is greater than the already greater are then update it
overAllMax = overAllMax < currentArea ? currentArea : overAllMax;
// change the pointer with respect to their heights
// if the height is lesser
if (height[i] < height[j])
i++;
// if it is greater
else if (height[i] > height[j])
j;
// if the heights are equal
else{
i++;
j;
}
}
// return the max area
return overAllMax;
}
Java Simple O(N) solution


@sati3000mangmail.com Could you kindly explain why this solution could always produce the right answer?


@demongaorui Yes. This solution is based on greedy strategy, where I am not able to find one counter example. If the area which I have found hitherto is the maximum then I should search for the next maximum area by moving one step forward from the smaller wall, if both heights are equal then move forward from both the walls. Hope it helps. Please let me know for any further questions.