LeetCode11. Container With Most Water

博客围绕给定非负整数数组,求能盛最多水的容器问题展开。介绍了该问题的描述及示例,指出储存水面积受限于短木板高度和木板间距,可从相距最远木板开始,移动矮木板求解,还提及最初想用按高度排序的思路及Java代码实现方向。

题目

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


储存水的面积受限于两个木板中较短的木板的高度,和两木板间的距离,所以我们可以从相距最远的两个木板开始,i指向最左边的木板,j指向最右边的木板,把每次得到的面积储存在max中,然后再移动两个木板中高度相对较小的木板 (i++或j --)

java 代码

public int maxArea(int[] height) {
        int i = 0, j = height.length - 1;
		int max = 0,area = 0;
		while(i != j) {
			if(height[i] < height[j]) {
				area = height[i] * (j - i);
				max = Math.max(area, max);
				i++;
			}else {
				area = height[j] * (j - i);
				max = Math.max(area, max);
				j--;
			}
			
		}
		
		return max;
    }

最初,是想着从高度最大的开始,再用一个数组记录他们最初的位置。把这些木板安照从高到低的顺序排列,对应的位置也同时排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值