Two pointer approach (11. Container with most water)
Q. 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 iis 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.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
There are two different versions' partial code. As you can see, version A during while loop temp(each iteration's area data) variable and mArea variable are compared and then it swapped if temp is bigger than mArea. However, in version B temp variable doesn't need as I used max built-in function. Interestingly, version A's runtime is slightly faster than version B.
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
headIdx = 0
tailIdx = len(height) - 1
mArea = 0
while(headIdx < tailIdx):
# Version A
temp = min(height[headIdx], height[tailIdx]) * (tailIdx - headIdx)
if mArea < temp:
mArea = temp
# Version B
#mArea = max(mArea, min(height[headIdx], height[tailIdx]) * (tailIdx - headIdx))
if height[headIdx] < height[tailIdx]:
headIdx += 1
else:
tailIdx -= 1
return mArea
reference site : https://leetcode.com/problems/container-with-most-water/solution/