height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
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.
Example 2:
Input: height = [1,1] Output: 1
Constraints:
n == height.length2 <= n <= 1050 <= height[i] <= 104배열, 투 포인터, 그리디
이 문제는 수직선들의 높이를 나타내는 정수 배열 height가 주어졌을 때, 두 개의 선을 선택하여 x축과 함께 컨테이너를 만들었을 때 담을 수 있는 물의 최대량을 구하는 문제입니다.
n인 정수 배열 height (2 ≤ n ≤ 100,000, 0 ≤ height[i] ≤ 10,000)i, j를 선택했을 때 면적 = (j - i) * min(height[i], height[j])입니다.이 문제를 해결하기 위해 투 포인터(Two Pointer) 알고리즘과 탐욕법(Greedy) 아이디어를 사용했습니다.
answer: 최대 면적을 저장할 변수, 0으로 초기화합니다.left: 배열의 시작 인덱스(0)를 가리키는 왼쪽 포인터입니다.right: 배열의 마지막 인덱스(len(height) - 1)를 가리키는 오른쪽 포인터입니다.while left < right: 조건으로 두 포인터가 만나기 전까지 반복합니다.(right - left) * min(height[left], height[right])로 계산합니다.answer = max(answer, 현재_면적)을 통해 지금까지의 최대값을 유지합니다.if height[left] > height[right]: 이면 오른쪽 선이 더 낮으므로 right -= 1하여 오른쪽 포인터를 왼쪽으로 한 칸 이동시킵니다.else: (왼쪽 선이 낮거나 같으면) left += 1하여 왼쪽 포인터를 오른쪽으로 한 칸 이동시킵니다.left >= right) 모든 유효한 쌍을 확인한 것이므로 최종 answer를 반환합니다.left, right)가 각각 배열의 양 끝에서 시작하여 중앙으로 이동하며 최대 한 번씩만 방문합니다. 전체 원소 수 N에 비례하는 연산만 수행하므로 선형 시간입니다.left, right)와 최대값 저장 변수(answer) 등 상수 개수의 변수만 사용하므로 입력 크기와 무관하게 일정한 메모리를 사용합니다.class Solution:
def maxArea(self, height: List[int]) -> int:
answer = 0
left = 0
right = len(height) - 1
while left < right:
answer = max(answer,(right-left) * min(height[left],height[right]))
if height[left] > height[right]:
right -= 1
else:
left += 1
return answer
# 100000