일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- API
- UI
- html
- js
- CSS
- Linux
- vscode
- CS
- PRISMA
- ts
- PyTorch
- python
- ML
- postgresql
- review
- ps
- react
- mongo
- nodejs
- GAN
- SOLID
- C++
- Three
- frontend
- figma
- CV
- backend
- DB
- Express
- Git
- Today
- Total
아카이브
[PS] Leet | 11. 가장 큰 컨테이너 본문
문제
You are given an integer array 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.
예시
Exampe 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
조건
- n == height.length
- 2 <= n <= 105
- 0 <= height[i] <= 104
답
양 끝을 시작으로 범위를 좁혀가면서 각 경우에 대해 최댓값을 비교하는 two-pointer 알고리즘을 사용합니다.
왼쪽 벽이 오른쪽 벽보다 낮을 때는 오른쪽 벽의 높이와 관계 없이 최소 높이가 결정되므로, 왼쪽 벽만 이동합니다.
반대의 경우에는 같은 이유로 오른쪽 벽만 이동합니다.
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
let maxAreaValue = 0;
let left = 0;
let right = height.length - 1;
while (left < right) {
let area = 0;
if (height[left] < height[right]){
area = height[left] * (right - left);
left++;
} else {
area = height[right] * (right - left);
right--;
}
maxAreaValue = Math.max(maxAreaValue, area);
}
return maxAreaValue;
};
시간 복잡도 : O(n)
공간 복잡도 : O(1)
'CS > PS' 카테고리의 다른 글
[PS] Leet | 300. 가장 긴 증가 수열 (0) | 2025.04.02 |
---|---|
[PS] Leet | 322. 동전 교환 (0) | 2025.03.28 |
[PS] 같은 수의 뉴런 (0) | 2025.03.21 |
[PS] Leet | 15. 세 개의 합 (0) | 2025.03.21 |
[PS] 가장 가까운 두 수 (0) | 2025.03.21 |