11. Container With Most Water-贪心

leetcode

Posted by chl on May 20, 2019

题目

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. image

题意

给定一个整型数组,以x轴为底,该数组中元素为对应位置的高,求任意两竖直线为杯壁,何时盛水最多。

题解

贪心的思想,使用两个指针,一个位于头部,一个位于尾部。做出当前看来是最好的选择,此时距离最远且如果较短那边杯壁为第二高,那么所得容量最大。接着遍历下一个元素,那边短就往高的那边靠近,同时维护一个变量max,记录每一次容量的最大值。

代码

func maxArea(height []int) int {
    maxContain := 0
    start,end := 0,len(height)-1
    for start<end{
        min := Min(height[start],height[end])
        maxContain = Max(maxContain,min*(end-start))
        if height[start]<height[end]{
            start++
        }else{
            end--
        }
    }
    return maxContain
}

func Max(m1,m2 int)int{
    if m1>m2{
        return m1
    }
    return m2
}

func Min(m1,m2 int)int{
    if m1<m2{
        return m1
    }
    return m2
}

总结

贪心算法的思想。没有固定框架,总是做出当前最好的选择,不从整体最优上考虑,他所做仅是在某种意义上的局部最优