leetcode Top100 (5) The container that holds the most water

/** 
 * Given an integer array height of length n. There are n vertical lines, and the two endpoints of the i-th line are (i, 0) and (i, height[i]). 
 * <p> 
 * Find two of the lines such that the container formed by them and the x-axis can hold the most water. 
 * <p> 
 * Returns the maximum amount of water that the container can store. 
 * <p> 
 * Note: You cannot tilt the container. 
 * Input: [1,8,6,2,5,4,8,3,7] 
 * Output: 49 
 * Explanation: The vertical line in the figure represents the input array [1,8,6,2,5,4,8 ,3,7]. In this case, the maximum value that the container can hold water (shown in blue) is 49. 
 */
public class top5 {

    /**
     * 双指针法
     */
    private static int largestSize(int[] num) {
        if (num.length == 0) {
            return 0;
        }

        int res = 0;
        int j = num.length - 1;
        int i = 0;
        while (i < j) {
            int largestSize = (j - i) * Math.min(num[i], num[j]);
            largestSize = Math.max(res, largestSize);
            res = largestSize;

            /*
            如果选择固定一根柱子,另外一根变化,水的面积会有什么变化吗?稍加思考可得:

    当前柱子是最两侧的柱子,水的宽度 ddd 为最大,其他的组合,水的宽度都比这个小。
    左边柱子较短,决定了水的高度为 3。如果移动左边的柱子,新的水面高度不确定,一定不会超过右边的柱子高度 7。
    如果移动右边的柱子,新的水面高度一定不会超过左边的柱子高度 3,也就是不会超过现在的水面高度。
            * */
            if (num[i] < num[j]) {
                i++;
            } else {
                j--;
            }
        }
        return res;
    }

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

Guess you like

Origin blog.csdn.net/harryptter/article/details/132876419