LeetCode 11. 盛最多水的容器

11 篇文章 0 订阅

题目如图:

最开始暴力求解:

    public static int CalculateMaxArea(int[] height) {
            int length = height.Length;
            int area = 0;
            //暴力法,从前往后遍历,计算每个数值和分别和其后的数值组成的区域面积,取最大值
            for (int i = 0; i < length; i++) {
                for (int j = length - 1; j > i; j--) {
                    area = Math.Max(area, (j - i) * Math.Min(height[i], height[j]));
                }

            }
            
            return area;
        }

后来优化了一下:

public static int CalculateMaxArea(int[] height) {
            int length = height.Length;
            int area = 0;
            //从两端开始向中间遍历,取两端数值小的向中间靠近,直至遍历所有数,取最大值
            int idx = 0, idy = height.Length - 1;
            while (idx < idy) {
                if (height[idx] > height[idy]) {
                    area = Math.Max(area, (idy - idx) * height[idy]);
                    idy--;
                }
                else {
                    area = Math.Max(area, (idy - idx) * height[idx]);
                    idx++;
                }
                
            }
            
            return area;
        }

 

 

题目来源https://leetcode-cn.com/problemset/all/ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值