題目

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

1
2
3
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

1
2
Input: height = [1,1]
Output: 1

解釋題目

height 是一個 integer array,每一個元素代表一個線段的高度。

任意兩條線段,沿著 X 軸方向,可以假想成一個容器,容器不能傾斜。

求容器最大能容納的水量。

思路

  1. Initial: 左指針指向最前面的 height,右指針指向最後面的 height。
  2. 開始計算水量,記錄最大水量。
  3. 若左邊的高度較矮,左指針就右移。若右邊的高度較矮,右指針就左移。移完指針後,回到第二步。
  4. 透過 Two Pointers,就能把所有狀況跑一遍。

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maxArea(vector<int>& height) {
int result = 0;
int left = 0;
int right = height.size() - 1;

while(left < right){
int area = (right - left) * min(height[left], height[right]);
result = max(result, area);
if(height[left] <= height[right])
left++;
else
right--;
}

return result;
}
};