[leetcode] 11. Container With Most Water

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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 and n is at least 2.
container

分析

题目的意思是:有一堆柱子,现在要选两根柱子,使得围成的面积能够装的水最多。

  • 一是两边往中间找,二是每次放弃最短的版。
    这么做的原因在于:从起点和终点开始找,宽度最大,这时每移动一次其中一个点,必然宽度变小。
    如此一来,想求最大,只有高度增长才有可能做到,去掉限制----短板,即放弃高度较小的点。
  • 本质上是一种贪心的算法,如果没有想到从两头向中间遍历,这道题就有点麻烦。

C++ 代码

class Solution {
public:
    int maxArea(vector<int>& height) {
        int low=0;
        int high=height.size()-1;
        int max_area=0;
        while(low<high){
            int min_height=min(height[low],height[high]);
            int len=high-low;
            max_area=max(max_area,min_height*len);
            if(height[low]<height[high]){
                low++;
            }else{
                high--;
            }
        }
        return max_area;
    }
};

Python 代码

用贪心的算法,思路跟C++的一样。

class Solution:
    def maxArea(self, height: List[int]) -> int:
        low=0
        high = len(height)-1
        max_area=0
        while(low<high):
            width=min(height[low],height[high])
            area = (high-low)*width
            max_area=max(max_area,area)
            if(height[low]<height[high]):
                low+=1
            else:
                high-=1
        return max_area

参考文献

[编程题]container-with-most-water

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值