LeetCode 11: Container With Most Water Solution

Master LeetCode problem 11 (Container With Most Water), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

11. Container With Most Water

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 11 (Container With Most Water)?

This page provides optimized solutions for LeetCode problem 11 (Container With Most Water) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 11 (Container With Most Water)?

The time complexity for LeetCode 11 (Container With Most Water) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 11 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 11 in Java, C++, or Python.

Back to LeetCode Solutions