11. Container With Most Water

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;
    }
};

运行结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值