leetcode 011 Container With Most Water
第6天
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.
大意 给一组数 对应位置为n的杆的高度height(i) 求出任意两个杆和x轴围城的水桶装水最多是多少
看题意 定义两个pointer i指左边的杆 j指右边的杆
在 j 的右端没有一条线会比它高! 假设存在 k | ( j < k && ak > aj) ,那么 由 ak> aj,所以 min( ai,aj, ak) =min(ai,aj) ,所以由i, k构成的容器的容积C’ = min(ai,aj ) * ( k-i) > C,与C是最值矛盾,所以得证j的后边不会有比它还高的线;
同理 i的左边也是一样 所以最大的容积只能在[i,j]里面 并且 最低高度得到提升
容积 = 宽 * 高 宽变小 高变大的时候 有可能增加容积 从短的那一段往里 挪- -
代码
class Solution:
# @param {integer[]} height
# @return {integer}
def maxArea(self, height):
lens = len(height)
i = 0
j = lens - 1
ans = 0
while j > i :
ans = max(min(height[i],height[j])*(j-i),ans)
if height[i] > height[j]:
j = j - 1
else:
i = i + 1
return ans