Forem

Stylus07
Stylus07

Posted on

5 4

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)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more