leetcode---C++实现---11. Container With Most Water(盛最多水的容器)
题目
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
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:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
解题思路
本题想要计算区间上能组成的最大面积,两条边的组成为:两条vertical line中较矮的高度,两条vertical line的水平距离。
当两条vertical line中有一条较高时:
若将较高的那条line往里移,在较高line的高度不变时,移动后的两条line的水平距离缩小了,只能比原先的距离更小,因此该情况不进行计算考虑;
若固定较高line,将较短的line往里移,有可能遇到更高的line,有可能出现更大的面积,此情况需要计算,在所有计算的面积中选出最大面积即可。
算法实现
#include <algorithm>
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int area = 0;
while (left < right)
{
int curArea = min(height[left], height[right]) * (right - left);
area = max(curArea, area);
if (height[left] < height[right])
++left;
else
--right;
}
return area;
}
};