一道有趣的面试 :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 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.
这里写图片描述

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

题目大意是,给定若干条垂直线,顺着x轴依次排列,要求找出其中最大的装水面积。

解法一:暴力求解
枚举任意两个垂直线,复杂度是O(N^2)。
这个方法很容易理解,不做解释。

解法二:贪心求解
维护左边界 L 和右边界 R ,边界之间的装水面积是 C = min(Input[L], Input[R]) * (R-L)
之后更新左右边界,如果Input[L] < Input[R],则左边界+1,否则右边界-1。
复杂度为O(N)。
这个方法很巧妙,但是理解起来不是那么直观。

这也是这道题目最有趣的地方,给大家分享一个理解思路:
可以把这个过程理解为每次减少不必要的计算,
如果Input[L] < Input[R],那么[L, R-1]的装水面积一定小于[L, R],思考一下为什么?原因如下:
由于装水面积取决于两个部分:边界间距 R-L,边界之间的较小者(木桶原理)。
显然[L, R-1]的边界间距小于[L, R]
min(Input[L], Input[R-1]) <= min(Input[L], Input[R]),这个条件是成立的,不论Input[R-1]的值是多少。

所以,最终答案一定不在[L, R-1]内,可以将左边界+1,剩余的可能性存在于[L+1, R]中。

最后再留一个问题:
如果Input[L] == Input[R],此时应该移动哪个边界,为什么?

给出这个题目的链接:
https://leetcode.com/problems/container-with-most-water/description/


欢迎大家关注我的公众号

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值