https://leetcode.com/problems/container-with-most-water/
找出面積最大的,回傳面積
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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.
暴力解 O(n^2)
雙指針 O(n)
class Solution:
def maxArea(self, height: List[int]) -> int:
l = 0
r = len(height) - 1
max_area = 0
while l < r:
area = (min(height[l], height[r])) * (r - l)
max_area = max(max_area, area)
# pointer 往牆比較矮的那一方移動
if height[l]>height[r]:
r -= 1
else:
l += 1
return max_area
time complexity: O(n), n for the length of height array
space complexity: O(1)