|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: easy |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Two Pointers |
| 8 | + - Greedy |
| 9 | +--- |
| 10 | + |
| 11 | +# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/description/) |
| 12 | + |
| 13 | +## Description |
| 14 | + |
| 15 | +Given an integer array `height` of length `n`, where each element represents the height of a vertical line drawn at position `i`, with endpoints at `(i, 0)` and `(i, height[i])`, your task is to determine the maximum amount of water that can be contained between any two lines and the x-axis. |
| 16 | + |
| 17 | +Return the maximum water volume that the container can store. |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | +``` |
| 21 | +Input: height = [1,6,5,5,4,1,7,1] |
| 22 | +Output: 36 |
| 23 | +Explanation: In this case, the max area of water ([6,5,5,4,1,7]) the container can contain is 36. |
| 24 | +``` |
| 25 | + |
| 26 | +**Example 2:** |
| 27 | +``` |
| 28 | +Input: nums = [2,2] |
| 29 | +Output: 2 |
| 30 | +``` |
| 31 | + |
| 32 | + |
| 33 | +**Constraints:** |
| 34 | +`n == height.length` |
| 35 | +`2 <= n <= 10^5` |
| 36 | +`0 <= height[i] <= 10^4` |
| 37 | + |
| 38 | +## Solution |
| 39 | + |
| 40 | +Simply put, we calculate the maximum area of the rectangle and return it. The formula shrinks inward, with the highest point as the side. |
| 41 | + |
| 42 | +```java |
| 43 | +class Solution { |
| 44 | + public int maxArea(int[] height) { |
| 45 | + int left = 0, right = height.length - 1; |
| 46 | + int maxArea = 0; |
| 47 | + while (left < right) { |
| 48 | + int area = (right - left) * Math.min(height[left], height[right]); |
| 49 | + maxArea = Math.max(maxArea, area); |
| 50 | + if (height[left] < height[right]) { |
| 51 | + left++; |
| 52 | + } else { |
| 53 | + right--; |
| 54 | + } |
| 55 | + } |
| 56 | + return maxArea; |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +```python |
| 62 | +class Solution: |
| 63 | + def maxArea(self, height: list[int]) -> int: |
| 64 | + left, right = 0, len(height) - 1 |
| 65 | + max_area = 0 |
| 66 | + while left < right: |
| 67 | + max_area = max(max_area, min(height[left], height[right]) * (right - left)) |
| 68 | + if height[left] < height[right]: |
| 69 | + left += 1 |
| 70 | + else: |
| 71 | + right -= 1 |
| 72 | + return max_area |
| 73 | +``` |
| 74 | + |
| 75 | + |
| 76 | +## Complexity |
| 77 | + |
| 78 | +- Time complexity: $$O(n^2)$$ |
| 79 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 80 | + |
| 81 | +- Space complexity: $$O(n)$$ |
| 82 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
| 83 | + |
0 commit comments