题解 | #盛水最多的容器#

盛水最多的容器

https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47

package com.hhdd.双指针;

/**
 * 不会做
 *
 * @Author huanghedidi
 * @Date 2022/8/10 23:38
 */
public class 盛水最多的容器 {

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

    /**
     * 双指针 分别指向头尾
     * area = min(height[i],height[j]) * (j-i+1)
     *
     * @param height
     * @return
     */
    public static int maxArea(int[] height) {
        // write code here
        int left = 0;
        int right = height.length - 1;
        int res = 0;
        while (left < right) {
            int tmp = (right - left ) * Math.min(height[left], height[right]);
            res = Math.max(res, tmp);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return res;
    }

}

全部评论

相关推荐

09-24 18:25
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务