Container With Most Water

styluso7

Stylus07

Posted on May 3, 2022

Container With Most Water

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

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.

Notice that you may not slant the container.

Problem statement taken from: https://leetcode.com/problems/container-with-most-water/


Brute Force Approach

var maxArea = function (heights) {
    let maxArea = 0;
    for (let p1 = 0; p1 < heights.length; p1++) {
        for (let p2 = p1 + 1; p2 < heights.length; p2++) {
            const length = Math.min(heights[p1], heights[p2]);
            const width = p2 - p1;
            const area = length * width;
            maxArea = Math.max(area, maxArea);
        }
    }
    return maxArea;
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(n^2)
Space Complexity : O(1)

Optimized Approach

    let maxArea = 0, p1 = 0, p2 = heights.length - 1;
    while (p1 < p2) {
        const height = Math.min(heights[p1], heights[p2]);
        const width = p2 - p1;
        const area = height * width;
        maxArea = Math.max(maxArea, area);
        if (heights[p1] <= heights[p2]) {
            p1++;
        } else {
            p2--;
        }
    }
    return maxArea;
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(n)
Space Complexity : O(1)

💖 💪 🙅 🚩
styluso7
Stylus07

Posted on May 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Container With Most Water
leetcode Container With Most Water

May 3, 2022