11. Container With Most Water [Medium]

11. Container With Most Water

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Constraints:

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Example
image

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

思路

求最大面积,那影响面积的两个条件就是长和宽,宽就是数组的值,长就是元素之间相差的位数
其中决定宽的应该是一对值中较小的那个值,大的那个值能适配的肯定更多些,所以就移动小的那一位

题解

  • 无脑快速AC
    public int maxArea(int[] height) {
        int result, left, right, step;
        result = left = 0;
        right = height.length - 1;
        while (left < right) {
	    // 找宽
            int len = Math.min(height[left], height[right]);
	    // 算长
            step = right - left;
            result = Math.max(len * step, result);

	    // 这里要把移位放最后做,不然会直接跳过第一位,其中也会有左边等于右边的情况,这里就让左边移动了
            if (height[left] > height[right])
                right--;
            else
                left++;
        }
        return result;
    }
posted @ 2023-01-10 19:25  AaronTanooo  阅读(23)  评论(0)    收藏  举报