var maxArea = function (height) {
let left = 0;
let right = height.length - 1;
let maxArea = 0;
while (left < right) {
// 수조 면적이 가장 작은 변에 의해 제한된다.
let curHeight = Math.min(height[left], height[right]); // 세로
let curWidth = right - left; // 가로
maxArea = Math.max(maxArea, curHeight * curWidth); // 넓이
height[left] < height[right] ? left++ : right--;
}
return maxArea;
};
문제는 이런 식으로 위와 같이 가장 큰 면적의 수조를 구하는 문제다.(자세한 문제 설명은 아래 링크 참고)
수조 면적이 최대가 되어야 하는데, 이 면적은 height
배열의 가장 작은 요소에 의해 제한되기 때문에 curHeight
라는 변수를 따로 만들어 지속적으로 업데이트 시켜줘야 했다.
이후 양 쪽 포인터를 움직여 left
가 right
보다 커지는 시점까지 loop을 진행해서 최대 면적을 모두 검사한다.
저희 스터디원 분들의 풀이, 설명 항상 감사합니다!
수정, 지적을 환영합니다!
https://leetcode.com/problems/container-with-most-water/
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/submissions/