Skip to main content
  1. Posts/

leetcode 11. Container With Most Water (two pointer)

·1 min
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

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 {
 7
 8    public:
 9
10	int maxArea(vector<int>& height) {
11	    int res = 0 ;
12	    int n = height.size();
13	    int head = 0 ;
14	    int tail = n-1;
15	    while (head<tail)
16	    {
17		int h = min(height[head],height[tail]);
18		res = max(res,(tail-head)*h);
19		while (head<tail&&height[head]<=h) head++;
20		while (head<tail&&height[tail]<=h) tail--;
21	    }
22	    return res;
23
24
25	}
26
27};

Related