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

Container With Most Water

2016-07-31 19:50 344 查看
一、问题描述

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.
二、思路

本题难点在于理解题目。在二维坐标系中,求(i,0)(j,0)组成的线段乘以高度h组成的图形面积最大,是一道动态规划题目,我们可以采用双层for求解,但是那样显然不是最优的,我们采用两个指针,一前一后找到最大值存起来,如果当前的权值小于h,那么没必要计算,直接跳过,最后返回最大值。

三、代码

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