盛最多水的容器Java版(力扣)

盛最多水的容器

给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。

在这里插入图片描述
示例 2:
输入:height = [1,1]
输出:1

示例 3:
输入:height = [4,3,2,1,4]
输出:16

示例 4:
输入:height = [1,2,1]
输出:2

提示:
n = height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104

题意:其实就是求两个柱子之间的最大面积。

思路:从两边分别向里面遍历,哪边的柱子矮就移动这一侧的柱子向内移动,这样就可以保证移动后的面积会大于等于当前的面积。

详细题解:官方题解

正确代码:

class Solution {
    public int maxArea(int[] height) {

        int l=0,r= height.length-1;
        int ans=0;

        while(l<r){
            int maxx=(r-l)*Math.min(height[l],height[r]);

            ans =Math.max(maxx,ans);
            if(height[l]<= height[r]){
                l++;
            }else {
                r--;
            }
        }

        return ans;
    }
}

完整代码(含测试样例):

package com.Keafmd.April.day13;

/**
 * Keafmd
 *
 * @ClassName: ContainerWithMostWater
 * @Description: 盛最多水的容器 https://leetcode-cn.com/problems/container-with-most-water/
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-13 9:30
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class ContainerWithMostWater {
    public static void main(String[] args) {
        Solution0413 solution0413= new Solution0413();
        int [] height = {1,3,2,5,25,24,5};
        int re = solution0413.maxArea(height);
        System.out.println("re = " + re);
    }
}
class Solution0413 {
    public int maxArea(int[] height) {

        int l=0,r= height.length-1;
        int ans=0;

        while(l<r){
            int maxx=(r-l)*Math.min(height[l],height[r]);

            ans =Math.max(maxx,ans);
            if(height[l]<= height[r]){
                l++;
            }else {
                r--;
            }
        }

        return ans;
    }
}

输出结果:

re = 24

Process finished with exit code 0

看完如果对你有帮助,感谢点赞支持!
如果你是电脑端,看到右下角的 “一键三连” 了吗,没错点它[哈哈]

在这里插入图片描述
加油!

共同努力!

Keafmd

  • 21
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

牛哄哄的柯南

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

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

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

打赏作者

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

抵扣说明:

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

余额充值