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/
'<개인공부> - IT > [Python]' 카테고리의 다른 글
Best time to buy and sell stock II (1-line python code) (0) | 2019.01.15 |
---|---|
13. Roman to Integer (0) | 2019.01.12 |
Python in operator (Regular Expression Matching) (0) | 2019.01.10 |
What does if __name__ == “__main__”: do? (0) | 2018.09.15 |
Python Multiple return values (Tuple, Dict) (0) | 2018.08.23 |