leetcode 11. Container With Most Water (two pointer)
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.
题意:n条竖直的线段 (i,0)->(i,a[i]),从中选2条,和x轴共同组成一个开口的容器,问容器的最大面积。
思路:一开始想错了,以为是最大连续矩形面积...还在想leetcode竟然考单调栈???
然而实际上只取两个线段,中间的线段有没有,长度,都是无所谓的。
因此two pointer就好了。。。
1/* ***********************************************
2Author :111qqz
3Created Time :2017年04月13日 星期四 18时06分42秒
4File Name :11.cpp
5 ************************************************ */
6class Solution {
public:
1 int maxArea(vector<int>& height) {
2 int res = 0 ;
3 int n = height.size();
4 int head = 0 ;
5 int tail = n-1;
6 while (head<tail)
7 {
8 int h = min(height[head],height[tail]);
9 res = max(res,(tail-head)*h);
10 while (head<tail&&height[head]<=h) head++;
11 while (head<tail&&height[tail]<=h) tail--;
12 }
13 return res;
}
};