Java: Container With Most Water

Thought Process

To solve the problem of finding the maximum area formed by two lines in a container, we can use the two-pointer approach. We start with two pointers, one at the beginning (left) and one at the end (right) of the array. The area is calculated as the minimum of the two heights multiplied by the distance between the pointers. We then move the pointer with the smaller height inward, as moving the taller pointer would not increase the area. This process continues until the pointers meet, ensuring that we find the maximum possible area efficiently.

class Solution {
    public int maxArea(int[] height) {
              
        int left = 0;
        int right = height.length - 1;
      
        int maxArea = -1;
        while(left<right){
      
            int area = Math.min(height[left],height[right])*(right-left);
            maxArea = Math.max(maxArea,area);
      
            if(height[left] < height[right]){
                left++;
            }
            else{
                right--;
            }
        }
        return maxArea;
    }
}

Code Complexity

Time Complexity: O(n)

The algorithm iterates through the array once using the two-pointer approach, making it linear in time complexity. Each step involves constant-time operations.

Space Complexity: O(1)

The algorithm uses a constant amount of extra space, as it only stores a few variables for tracking the pointers and the maximum area.

Code copied!