DEV Community

codingpineapple
codingpineapple

Posted on

2 1

LeetCode 11. Container With Most Water (javascript solution)

Description:

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.

Solution:

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

// 2 pointers
var maxArea = function(height) {
    // Max amountof water
    let max = 0
    // Pointer to move possible heights
    let left = 0
    let right = height.length-1
    // Use 2 pointers to find the max area
    while(left < right) {
        // Current area
        const area = Math.min(height[left], height[right]) * (right - left)
        // Check if current area is greater than previous max
        max = Math.max(max, area)
        // Move the pointer that has the lowest height
        if(height[left]>height[right]) {
            right--
        } else {
            left++
        }
    }
    return max
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay