Container With Most Water

来源:互联网 发布:git mac客户端 编辑:程序博客网 时间:2024/05/01 04:39

一、问题描述

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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;    }};


1 0