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
分析:
//面积总是受到较小高度的影响
//这里设置一个前后指针,那么面积S=min(height[left], height[right]) * (right-left+1)
//显然,高度越高对面积越有利,长度越长,对面积越有利
//所以我们要找到尽量保证长度的前提下,增大高度
//所以使用前后指针,先使得长度最大,然后根据高度大小进行长度缩小
//由于受到较高度的影响,当前后指针高度较小的时候,需要进行移动
//移动过程中记录面积Max
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int max_area = INT_MIN;
int left = 0, right = n - 1; //类似于快速排序,前后指针
//面积总是受到较小高度的影响
//这里设置一个前后指针,那么面积S=min(height[left], height[right]) * (right-left+1)
//显然,高度越高对面积越有利,长度越长,对面积越有利
//所以我们要找到尽量保证长度的前提下,增大高度
//所以使用前后指针,先使得长度最大,然后根据高度大小进行长度缩小
//由于受到较高度的影响,当前后指针高度较小的时候,需要进行移动
//移动过程中记录面积Max
while (left < right)
{
int cur_s = min(height[left], height[right])*(right - left);
max_area = max(max_area, cur_s);
if (height[left] <= height[right])
left++;
else
right--;
}
return max_area;
}
private:
int min(int a, int b)
{
return a < b ? a : b;
}
int max(int a, int b)
{
return a > b ? a : b;
}
};