public class Solution {
public int maxArea(int[] height) {
int result = 0;
for(int i=0,j=height.length1;i<j;){
// get current area
int area = Math.min(height[i],height[j])*(ji);
result = Math.max(area,result);
//move the pointers
if(height[i]<height[j]){
i++;
}
else {
j;
}
}
return result;
}
}
Java two pointer


public int maxArea(int[] height) { int index1 = 0; int index2 = height.length  1; int maxArea = 0; while (index1 < index2) { int minHeight = Math.min(height[index1], height[index2]); maxArea = Math.max(maxArea, (index2  index1) * minHeight); // Shift smaller one while (minHeight >= height[index1] && index1 < index2) index1++; while (minHeight >= height[index2] && index2 > index1) index2; } return maxArea; } // Complexity : O(n)
This was my final code. My initial code was very similar to the code above. Most of these codes basically uses the same overall idea but some microoptimization really increases the runtime. For instance using
Math.max()
is much faster than an if statement.
maxArea = Math.max(maxArea, area);
runs faster than doingif (area > maxArea) maxArea = area;
. Also declaring and assigning variables takes time it seems. so instead of assigningarea = (index2  index1) * minHeight
using it directly improves the runtime since you wont be using it again. I found that making these minor improvements significantly moved my answers through the runtime spectrum.Of course these microoptimizations are usually negligible in real life and are only good for fun exercises like these.