zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【算法hot-11】盛最多水的容器

算法容器 11 hot
2023-09-27 14:29:28 时间

盛最多水的容器

输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

img

public class LC004_11_maxArea {

    public static void main(String[] args) {
        int[] ints = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        System.out.println(maxArea(ints));
    }

    public static int maxArea(int[] height) {
        //每次都计算2个柱子的体积,算出最大值 双指针+贪心
        int left = 0, right = height.length - 1, ans = 0;
        while (left < right) {
            ans = height[left] < height[right] ?
                    Math.max(ans, (right - left) * height[left++]) :
                    Math.max(ans, (right - left) * height[right--]);
        }
        return ans;
    }
}