diff --git a/problems/container-with-most-water/README.md b/problems/container-with-most-water/README.md new file mode 100644 index 0000000..f45bf32 --- /dev/null +++ b/problems/container-with-most-water/README.md @@ -0,0 +1,50 @@ +# Container With Most Water + +LeetCode #: [11](https://leetcode.com/problems/container-with-most-water/) + +Difficulty: Medium + +Topics: Array, Two Pointers. + +## Problem + +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. + +Example 1: + +![Example 1](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg) + +```text +Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 +Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. +``` + +Example 2: + +```text +Input: height = [1,1] +Output: 1 +``` + +Example 3: + +```text +Input: height = [4,3,2,1,4] +Output: 16 +``` + +Example 4: + +```text +Input: height = [1,2,1] +Output: 2 +``` + +Constraints: + +- `n == height.length` +- `2 <= n <= 3 * 10^4` +- `0 <= height[i] <= 3 * 10^4` diff --git a/problems/container-with-most-water/maxArea.js b/problems/container-with-most-water/maxArea.js new file mode 100644 index 0000000..30a8cb7 --- /dev/null +++ b/problems/container-with-most-water/maxArea.js @@ -0,0 +1,25 @@ +/** + * @param {number[]} height + * @return {number} + */ +const maxArea = (height) => { + let left = 0 + let right = height.length - 1 + let area = 0 + + while (left < right) { + const w = right - left + const h = Math.min(height[left], height[right]) + area = Math.max(area, w * h) + + if (height[left] < height[right]) { + left++ + } else { + right-- + } + } + + return area +} + +module.exports = maxArea diff --git a/problems/container-with-most-water/maxArea.test.js b/problems/container-with-most-water/maxArea.test.js new file mode 100644 index 0000000..9b25b71 --- /dev/null +++ b/problems/container-with-most-water/maxArea.test.js @@ -0,0 +1,33 @@ +const maxArea = require('./maxArea') + +test('Example 1', () => { + const height = [1, 8, 6, 2, 5, 4, 8, 3, 7] + + const result = maxArea(height) + + expect(result).toStrictEqual(49) +}) + +test('Example 2', () => { + const height = [1, 1] + + const result = maxArea(height) + + expect(result).toStrictEqual(1) +}) + +test('Example 3', () => { + const height = [4, 3, 2, 1, 4] + + const result = maxArea(height) + + expect(result).toStrictEqual(16) +}) + +test('Example 4', () => { + const height = [1, 2, 1] + + const result = maxArea(height) + + expect(result).toStrictEqual(2) +})