LeetCode Array Medium 11. Container With Most Water

 Description


Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

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:

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

题目描述:给定n(n>=2)个非负整数,构成下面的图,找到两条线,它们与x轴一起形成一个容器,这样容器就含有最多的水。

思路:可以理解为求矩形的最大面积。将y轴的点到x轴的垂直距离作为矩形的一边,两个点的x轴的值的差作为另一边。求这两个边所形成的矩形的最大面积。

两个指针分别指向给定数组的头和尾,计算面积S=(两个点的y轴的最小值)* 两个点的x轴的差值。y轴的小的点在计算之后继续向中间靠拢。直到头尾指针相邻。

代码:

//11. Container With Most Water
        public int MaxArea(int[] height)
        {
            int maxArea = int.MinValue;
            int lo = 0, hi = height.Length - 1;
            while(lo < hi)
            {
                int temp = 0;
                if(height[lo] <= height[hi])
                {
                    temp = height[lo] * (hi - lo);
                    lo++;
                }
                else
                {
                    temp = height[hi] * (hi - lo);
                    hi--;
                }
                if (temp > maxArea)
                    maxArea = temp;
            }
            return maxArea;
        }

原文地址:https://www.cnblogs.com/c-supreme/p/9560211.html