LeetCode Daily Question 21

5 月 5 日 每日一题


题目:11. Container With Most Water

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.

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.

思路

本题是关于双指针和贪心的题目,Greedy 的逻辑为:从可能最大的宽度起始,如果左边小,则 left++,如果右边小则 right–。因为水面高度永远取最小,所以如果移动大的一边,体积必然下降。如果 greedy 后得出的体积比当前的 maxArea 大,则修改当前 maxArea。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea = 0;
int left = 0;
int right = static_cast<int>(height.size() - 1);
while(left != right){
maxArea = max(min(height[left], height[right]) * (right - left), maxArea);
if(height[left] < height[right])
left++;
else
right--;
}
return maxArea;
}
};
  1. 5 月 5 日 每日一题
    1. 题目:11. Container With Most Water
    2. 思路
    3. 代码