Skip to content

Commit

Permalink
Add solution for #11 Container With Most Water.
Browse files Browse the repository at this point in the history
  • Loading branch information
ecgan committed Feb 17, 2021
1 parent ffacd5e commit a7909d4
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 0 deletions.
50 changes: 50 additions & 0 deletions problems/container-with-most-water/README.md
Original file line number Diff line number Diff line change
@@ -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`
25 changes: 25 additions & 0 deletions problems/container-with-most-water/maxArea.js
Original file line number Diff line number Diff line change
@@ -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
33 changes: 33 additions & 0 deletions problems/container-with-most-water/maxArea.test.js
Original file line number Diff line number Diff line change
@@ -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)
})

0 comments on commit a7909d4

Please sign in to comment.