Container With Most Water

来源:互联网 发布:罗曼尼康帝 知乎 编辑:程序博客网 时间:2024/05/09 10:59

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 linei 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.

水题,就是从两边向中间计算,每次计算出一个area,在用一个maxarea在存储最大值,计算一次后,去掉值小的,移位运算。其实就是计算min(ai, aj) * (i - j)

int maxArea(vector<int> &height) {        int high = (int)height.size() - 1;        int low = 0;        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;    }

0 0
原创粉丝点击