LeetCode — 11. Container With Most Water
題目連結:https://leetcode.com/problems/container-with-most-water/description/
LeetCode — 11. Container With Most Water
題目連結:https://leetcode.com/problems/container-with-most-water/description/
先看題目
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]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:

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:
Input: height = [1,1]
Output: 1
Constraints:
n == height.length2 <= n <= 1050 <= height[i] <= 104
解題思路
管他的,先暴力解看看,沒有超時就不管了XD
- 找到最高的線條的高度:
maxHeight - 從高度 0 到
maxHeight依序找到最外圍的線條並計算容量 - 取最高的容量輸出
這題真的很簡單(可能 Hard 寫太多,Medium 的題目瞬間變的很簡單):
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int maxHeight = 0;
int maxWater = 0;
for (int i = 0; i < n; i++) {
maxHeight = max(maxHeight, height[i]);
}
for (int i = 0; i <= maxHeight; i++) {
int leftIndex = -1;
int rightIndex = -1;
for (int j = 0; j < n; j++) {
if (height[j] >= i) {
leftIndex = j;
break;
}
}
for (int j = n - 1; j >= 0; j--) {
if (height[j] >= i) {
rightIndex = j;
break;
}
}
if (leftIndex == rightIndex || leftIndex == -1) {
break;
}
maxWater = max(maxWater, i * (rightIndex - leftIndex));
}
return maxWater;
}
};
執行結果
最後壓線 AC 通過,但耗時超高。後來看其他人的解法,他們是以遍歷線條為出發點,由外向內取較高的線條計算最大容量。寫競程的題目真的可以訓練邏輯思考能力。

這題的解題紀錄到這邊就結束了喔!如果有任何疑問或建議,歡迎來信詢問:sunyipingtw@icloud.com。記得追蹤加按讚~
메타데이터
- post_id
- 3d85b37be196
- slug
- leetcode-11-container-with-most-water-3d85b37be196
- url
- https://medium.com/@1Ping/leetcode-11-container-with-most-water-3d85b37be196
- canonical_url
- https://medium.com/@1Ping/leetcode-11-container-with-most-water-3d85b37be196
- author_url
- https://medium.com/@1Ping
- status
- ok
- fetched_at
- 2026-06-25 16:53:31