|
| 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 | + |
| 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