> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Container With Most Water

Leetcode Problem 11: Container With Most Water

Problem Summary

You are given an array height of n integers. Consider n vertical lines where line i has height height[i]. Find two lines that, together with the x-axis, form a container holding the most water. Return the maximum water volume. The water level is limited by the shorter line, and the volume equals the shorter height multiplied by the horizontal distance between the lines.

Constraints:

  • The array has between 2 and 100,000 elements.
  • Each height is a non-negative integer up to 10,000.

Techniques

  • Array
  • Two Pointers
  • Greedy

Solution

function maxArea(height: number[]): number {
    let first = 0
    let last = height.length - 1
    let maxArea = 0

    while (first < last) {
        let smallerSide = height[first] > height[last] ? height[last] : height[first]
        maxArea = Math.max(maxArea, smallerSide * Math.abs(last - first))

        if (height[first] > height[last]) {
            last--
        } else {
            first++
        }
    }

    return maxArea
};

console.log(maxArea([1,8,6,2,5,4,8,3,7]))