Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 6da5aa2

Browse files
authored
Create 11. Container With Most Water.md
1 parent 4170af0 commit 6da5aa2

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

11. Container With Most Water.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# 11. Container With Most Water
2+
3+
### 2022-02-23
4+
5+
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])`.
6+
7+
Find two lines that together with the x-axis form a container, such that the container contains the most water.
8+
9+
Return *the maximum amount of water a container can store*.
10+
11+
**Notice** that you may not slant the container.
12+
13+
14+
15+
**Example 1:**
16+
17+
![img](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg)
18+
19+
```
20+
Input: height = [1,8,6,2,5,4,8,3,7]
21+
Output: 49
22+
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.
23+
```
24+
25+
**Example 2:**
26+
27+
```
28+
Input: height = [1,1]
29+
Output: 1
30+
```
31+
32+
33+
34+
# Solution
35+
36+
```swift
37+
class Solution {
38+
func maxArea(_ height: [Int]) -> Int {
39+
guard height.count > 1 else {
40+
return 0
41+
}
42+
43+
var left = 0
44+
var right = height.count - 1
45+
var area = 0
46+
while left < right {
47+
var h = 0
48+
if height[left] < height[right] {
49+
h = height[left]
50+
left += 1
51+
} else {
52+
h = height[right]
53+
right -= 1
54+
}
55+
area = max(area, (right - left + 1) * h)
56+
}
57+
return area
58+
}
59+
}
60+
```

0 commit comments

Comments
 (0)