https://leetcode.com/problems/container-with-most-water/?envType=study-plan-v2&envId=leetcode-75

My first solving was using brute-force. I new this won’t be the optimal answer but there was no other way.
private static int maxArea(int[] height) {
int n = height.length;
//if the size of array is 2
if (n == 2) {
return Math.min(height[0], height[1]);
}
int maxP = Integer.MIN_VALUE;
int maxSize = Integer.MIN_VALUE;
//loop until before the end
for (int p = 0; p <= n - 2; p++) {
//if the stick is taller than the maxP
if (maxP < height[p]) {
for (int j = n - 1; j >= p + 1; j--) {
int size = (j - p) * Math.min(height[p], height[j]);
maxSize = Math.max(size, maxSize);
maxP = height[p];
}
}
}
return maxSize;
}
This is using optimal 2 pointers. I studied with most voted code at the discussion tab.
private static int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxSize = 0;
while (left < right) {
maxSize = Math.max(maxSize, (right - left) * Math.min(height[left], height[right]));
if (height[left] < height[right]) left++;
else if (height[left] > height[right]) {
right--;
} else {
left++;
right--;
}
}
return maxSize;
}
The problem "Container With Most Water" is a popular problem in coding interviews and contests. It involves finding the maximum area of water that can be contained between two vertical lines on a 2D plane. The two Underground pipe leaks Spain lines must be selected such that the area between them is maximized.