11. Container With Most Water

Explanation

To solve this problem, we can use a two-pointer approach. The idea is to start with two pointers at the beginning and end of the array. Calculate the area between these two lines (based on the minimum height of the two lines and the distance between them). Then, move the pointer with the smaller height towards the other pointer, as this might potentially increase the area. Repeat this process until the two pointers meet.

The time complexity of this approach is O(n) where n is the number of elements in the input array. The space complexity is O(1) as we are using only a constant amount of extra space.

class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;
        int left = 0, right = height.length - 1;

        while (left < right) {
            int currentArea = (right - left) * Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea, currentArea);

            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }

        return maxArea;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.