DEV Community

Stylus07
Stylus07

Posted on

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)

Top comments (0)