LeetCode--Array--Container With Most Water (Medium)

Posted victorxiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode--Array--Container With Most Water (Medium)相关的知识,希望对你有一定的参考价值。

11. Container With Most Water (Medium)

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 line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

技术图片

    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.

solution

第一种解法:暴力解法,也是最容易想到的解法

class Solution 
    public int maxArea(int[] height) 
        int max = 0;
        for (int i = 0; i < height.length; i++)
        
            for (int j = i + 1; j <height.length; j++)
            
                int s = 0;
                if (height[i] > height[j])
                    s = height[j] * (j - i);
                else
                    s = height[i] * (j - i);    
                max = s > max ? s : max;   
            
        
        return max;
    

第二种解法:贪心算法

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

reference
https://leetcode.com/articles/container-with-most-water/

总结

第一种暴力算法很容易想到,但时间复杂度为O(n^2);第二种使用的是贪心算法,时间复杂度为O(n)。

Notes
1.可以在暴力算法的基础上得到贪心算法;

以上是关于LeetCode--Array--Container With Most Water (Medium)的主要内容,如果未能解决你的问题,请参考以下文章