DEV Community

smolthing
smolthing

Posted on • Edited on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs