11. Sheng most water containers
Topic links: https://leetcode-cn.com/problems/container-with-most-water/
Difficulty: Medium
Title Description
You give a non-negative integer n a1, a2, ..., an, a point (i, ai) each represents the number of coordinates. Videos n lines in vertical coordinate, i is a vertical line two end points are (i, AI) and (i, 0). Find out the two lines, which together with the container so that the x-axis configuration can accommodate up water.
Note: You can not tilting the container, and the value of n is at least 2.
FIG vertical line represents the input array [1,8,6,2,5,4,8,3,7]. In this case the maximum container capable of holding water (indicated as blue) of 49.
Examples
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Code
Which 法1
is to write, for large amounts of data will be reported error timeout, 法2
reference others
class Solution:
def maxArea(self, height: List[int]) -> int:
''' 法1:暴力方法:(对于大量数据会超时)
max_contain = 0
for i in range(len(height)):
temp = 0
for j in range(len(height[i:])):
h = height[i] if height[i] < height[i+j] else height[i+j]
temp = h * j
if temp > max_contain:
max_contain = temp
return max_contain
'''
# 法2:
i, j, area = 0, len(height) - 1, 0
while i < j:
if height[i] < height[j]:
area = max(area, height[i] * (j - i))
i += 1
else:
area = max(area, height[j] * (j - i))
j -= 1
return area
# 其中法二参考自:
# 作者:jutraman
# 链接:https://leetcode-cn.com/problems/container-with-most-water/solution/pythonsheng-zui-duo-shui-de-rong-qi-by-jutraman/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。