11. Container With Most Water

3991 단어 leetcodeleetcode

💡풀이

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라는 변수를 따로 만들어 지속적으로 업데이트 시켜줘야 했다.

이후 양 쪽 포인터를 움직여 leftright보다 커지는 시점까지 loop을 진행해서 최대 면적을 모두 검사한다.

저희 스터디원 분들의 풀이, 설명 항상 감사합니다!

수정, 지적을 환영합니다!

문제 링크

https://leetcode.com/problems/container-with-most-water/

LeetCode GitHub

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/submissions/

좋은 웹페이지 즐겨찾기