11. Container With Most Water

来源:互联网 发布:淘宝特卖网 编辑:程序博客网 时间:2024/06/05 13:35

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.

解法思路:这道题其实求不规则矩形的最大长方形面积,依然是贪心算法,我们首先计算出首尾相连的矩形的长方形面积,因为这是长最大的矩形的面积,接下来我们想找到这最优解的话,肯定是要向中间移动,而这移动必然使得长度减少,那么只有高度增高,才能使得面积更大;因此我们找出更高的最小高,所以要分为两种情况,当左边的高低于右边的高,我们必然使得,左边的点向右移,找到第一个比他高的边,使得面积更大,左边高于右边时,同理,同理左边移动,找到更高的边;

class Solution {public:    int maxArea(vector<int>& height) {        int containerWater = 0;        int  pt,i,j;        int head = 0; int end = height.size()- 1;        while (end > head){           pt = min(height[head], height[end]);           containerWater = max(containerWater,pt*(end- head));           if(height[head] < height[end]) {               i = 1;               while(height[head] > height[head + i]) i++;               head += i;           }else{               j = 1;               while(height[end]> height[end-j]) j++;               end -= j;           }        }        return containerWater;    }};

运行结果