您的位置:首页 > 大数据 > 人工智能

leetcode -- Container With Most Water

2014-12-05 14:38 537 查看
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.实际上就是求:max(|ai - aj|*min(ai, aj)) i,j=0,1,2,...n
分析:

(i) 对于某个a[i],(i=1,2,..n),如果a[i-1]>=a[i], 则显然不可能在a[i]取最大值;

(ii)对于某个a[i],从尾部开始寻找a[j]。

(i)a[j]< a[i]情况:如果a[j-k] <= a[j], k=1,2,3..,显然不可能在a[j-k]处取最大值

(ii)一旦存在某个a[j]>=a[i], 则最大值不可能在(i,j)区间内

class Solution {
public:
int maxArea(vector<int> &height) {
int a, b, max_b;
int area,  area_max, g_area_max = 0;
for(a = 0; a != height.size(); a++)
{
if(a >0 && height[a] <= height[a - 1])  continue;
b = height.size() - 1; max_b = b;
area_max = (max_b - a) * min(height[a], height[max_b]);
while(a < b && height < height[a])
{
if(height[--b] > height[max_b])
{
area = (b - a) * min(height[a], height[b]);
if(area_max < area)
{
max_b = b;
area_max = area;
}
}
}
if(b > a)
{
area = (b - a) * height[a];
if(area_max < area)
{
max_b = b;
area_max = area;
}
}
if(g_area_max < area_max)
g_area_max = area_max;
}
return g_area_max;
}
};


[b]更好的方法 Here is a solution by n00tc0d3r from old discuss


思路:

(i) 假设a[left]和a[right]暂时的面积最大,left从0开始++, right从尾开始--

(ii)a[left]<a[right], 即临时最大面积为tmp_maxArea=(right-left)*a[left]

那么如果存在更大面积,那么一定是换掉左边的a[left](即存在更大的a[left]),所以left++

(iii)a[left]>a[right],同理需要right--

int maxArea(vector<int> &height) {
int len = height.size(), low = 0, high = len -1 ;
int maxArea = 0;
while (low < high) {
maxArea = max(maxArea, (high - low) * min(height[low], height[high]));
if (height[low] < height[high]) {
low++;
}
else {
high--;
}
}
return maxArea;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: