☃️ 문제
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.
길이가 n인 정수 배열 높이가 주어진다.
i번째 선의 두 끝점이 (i, 0)과 (i, height[i])가 되도록 n개의 수직선을 그린다.
컨테이너가 가장 많은 물을 포함하도록 x축과 함께 컨테이너를 형성하는 두 개의 선을 찾는다.
용기가 저장할 수 있는 최대 물의 양을 반환한다.
단 용기를 기울이면 안 됩니다.
☃️ 예시
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.
☃️ 풀이 설명
- 높이를 계산하기 위해 시작부터 옮겨갈 인덱스의 숫자를 left로, 끝부터 옮겨올 인덱스의 숫자를 right로 선언하였다.
- 그리고 반환해줄 값을 area로 선언하고 초기화를 하였다.
public int maxArea(int[] height) {
int left = 0;
int right = height.length -1;
int area = 0;
}
- left의 값이 right의 값보다 작으면 계속해서 반복문을 돌리면서 비교해주었다.
- 두 개의 높이 중 더 낮은 값의 높이가 컨테이너의 세로 높이이기 때문에 두 개의 값 중 더 작은 것을 수직 값에 넣어주었다.
- 길이는 right에서 left를 뺀 값이기 때문에 해당 값을 길이에 넣어주었다.
- 이 문제는 가장 큰 값을 구해야하는 문제이기 때문에 두개의 길이 값중에 작은 쪽의 인덱스 값을 계속해서 옮기며 확인해주었다.
- 그리고 마지막으로 반환할 때에는 컨테이너의 물의 양 즉, 컨테이너의 크기중 가장 큰 값을 반환해야하기 때문에 Math.max를 사용하여 비교한 후, 가장 큰 값을 반환시켜 주었다.
public int maxArea(int[] height) {
...
while (left < right) {
int vertical = Math.min(height[left], height[right]);
int length = right - left;
if (height[left] < height[right]) {
left++;
} else {
right--;
}
area = Math.max(area, vertical * length);
}
return area;
}
☃️ 최종 풀이
public int maxArea(int[] height) {
int left = 0;
int right = height.length -1;
int area = 0;
while (left < right) {
int vertical = Math.min(height[left], height[right]);
int length = right - left;
if (height[left] < height[right]) {
left++;
} else {
right--;
}
area = Math.max(area, vertical * length);
}
return area;
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 014.Longest Common Prefix JAVA (0) | 2023.01.04 |
---|---|
[LeetCode] 013. Roman to Integer JAVA (0) | 2022.12.30 |
[LeetCode] 012. Integer to Roman JAVA (0) | 2022.12.23 |
[LeetCode] 004. Median of Two Sorted Arrays JAVA (0) | 2022.12.22 |
[LeetCode] 008. String to Integer (atoi) JAVA (0) | 2022.12.21 |
댓글