LeetCode - Container With Most Water
The problem is described as following:
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.
My solution is as following:
class Solution:
# @param height, an integer[]
# @return an integer
def maxArea(self, height):
i, j, largest = 0, len(height)-1, 0
while i < j:
largest = max(largest, (j-i)*min(height[i], height[j]))
# move the index with lower value
if height[i] <= height[j]:
i += 1
else:
j -= 1
return largest
思路比较简单,只需要从两侧遍历,每次移动value较小的那个index就可以。如果试图遍历所有的组合 (i,j) 组合,会面临LTE的问题。