Leetcode 0011: Container With Most Water

题目描述:

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.

Example 1:
在这里插入图片描述

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.

Example 2:

Input: height = [1,1]
Output: 1

Example 3:

Input: height = [4,3,2,1,4]
Output: 16

Example 4:

Input: s = “aab”, p = “cab”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches “aab”.

Example 5:

Input: height = [1,2,1]
Output: 2

Constraints:

n == height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104

Time complexity: O(n)
双指针:
用两个指针 l,r 分别指向首尾,如果 height[r] >= height[l],则 l++;否则 r–,直到 l = r为止,每次迭代更新最大值。

证明来自 yxc https://www.acwing.com/solution/content/100/:
假设最优解对应的两条线的下标是 l′,r′ , 在 l, r 不断靠近的过程中,不妨假设 l 先走到 l′,则此时有 r′<r。反证,如果此时 height[l]≤ height[r],设 S 表示 l,r能盛多少水,S′ 表示 l′,r′能盛多少水,则:
S = min(height[l],height[r])∗(r−l)
=height[l]∗(r−l) > height[l]∗(r′−l) ≥min(height[l],height[r’])∗(r′−l)=S′
与 S′ 是最优解矛盾,因此 height[l]>height[r],所以 r 会一直走到 r′,从而得到最优解。

class Solution {
    
    
    public int maxArea(int[] height) {
    
    
        int l = 0;
        int r = height.length - 1;
        int res = 0;
        while(l < r){
    
    
            int h = Math.min(height[r], height[l]);
            res = Math.max(res, h*(r-l));
            if(height[r] >= height[l]){
    
    
                l++;
            }else{
    
    
                r--;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113808821