题目: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 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.
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:
代码语言:javascript复制Input: [1,8,6,2,5,4,8,3,7]
Output: 49
解答:
第一想法两个for循环,但是很明显没有通过。
参考:[LeetCode]题解(python):011-Container With Most Water
代码语言:javascript复制class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
size = len(height) # the size of height
maxm = 0 # record the most water
j = 0
k = size - 1
while j < k:
if height[j] <= height[k]:
maxm = max(maxm,height[j] * (k - j))
j = 1
else:
maxm = max(maxm,height[k] * (k - j))
k -= 1
return maxm
效率更高的方法:sample 48 ms submission
代码语言:javascript复制class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i,j,max_v=0,len(height)-1,0
while i<j:
if height[i]<height[j]:
short_p=height[i]
v=short_p*(j-i)
i =1
while i<j and height[i]<=short_p:
i =1
else:
short_p=height[j]
v=short_p*(j-i)
j-=1
while i<j and height[j]<=short_p:
j-=1
if v>max_v:
max_v=v
return max_v