N
(Leet Code JS)Container With Most Water 본문
11. Container With Most Water
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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
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
Example 3:
Input: height = [4,3,2,1,4] Output: 16
Example 4:
Input: height = [1,2,1] Output: 2
Constraints:
- n == height.length
- 2 <= n <= 105
- 0 <= height[i] <= 104
투포인터 알고리즘.
front와 back으로 각각 height 배열의 0번째 인덱스와 마지막 인덱스를 넣어서 시작한다.
while문으로 최대 넓이 구하기.
height 배열 중 [front]와 [back]에 있는 값을 비교하여 더 작은 값을 변으로 정한다.
해당 변으로 직사각형의 넓이를 구한 후, 범위를 좁힌다.
또한, answer과 비교하여 더 큰 값을 갱신시키면 된다.
/**
* @param {number[]} height
* @return {number}
*/
const maxArea = function(height) {
let front = 0;
let back = height.length - 1;
let answer = 0;
while(front < back){
let width = 0;
if(height[front] < height[back]){
width = height[front] * (back - front);
front++;
} else{
width = height[back] * (back - front);
back--;
}
answer = answer < width ? width : answer;
}
return answer;
};
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Combinations (0) | 2021.09.23 |
---|---|
(LeetCode JS)Permutation (0) | 2021.09.20 |
(Leet Code JS)Maximum Area of a Piece of cake after horizontal and vertical cuts (0) | 2021.09.14 |
(Leet Code c++)Maximum Area of a Piece of cake after horizontal and vertical cuts (0) | 2021.09.14 |
(Leet Code c++)Swap Nodes in Pairs (0) | 2021.09.10 |