DEV Community

smolthing
smolthing

Posted on • Updated on

11. Container With Most Water

Image description

Question

Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.

Steps

  1. Two pointers: start and end
  2. Choose the shorter height for area
  3. Move the pointer with shorter height

Python

class Solution:
    def maxArea(self, height: List[int]) -> int:

        start = 0
        end = len(height) - 1

        maxArea = 0

        while start < end:
            minHeight = min(height[start], height[end])
            length = end - start
            maxArea = max(maxArea, length * minHeight)

            if height[start] > height[end]:
                end -= 1
            else:
                start += 1

        return maxArea
Enter fullscreen mode Exit fullscreen mode
height =
[3,5,2,6,5,2]

Output = 15
Enter fullscreen mode Exit fullscreen mode

Java

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

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

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

        return maxArea;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)