[leetcode, JS] 11. Container With Most Water

mxxn·2023년 9월 14일
0

leetcode

목록 보기
75/198

문제

문제 링크 : Container With Most Water

풀이

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let leftIndex = 0;
    let rightIndex = height.length - 1;
    let maxStoredWater = 0;

    while (leftIndex < rightIndex) {
        const leftHeight = height[leftIndex];
        const rightHeight = height[rightIndex];
        const width = rightIndex - leftIndex;
        const smallerHeight = leftHeight < rightHeight ? leftHeight : rightHeight;
        const storedWater = width * smallerHeight;

        maxStoredWater = storedWater > maxStoredWater ? storedWater : maxStoredWater;
        smallerHeight == leftHeight ? leftIndex++ : rightIndex--;
    }

    return maxStoredWater;
};
  1. 풀이를 보고 진행
  2. leftIndex, rightIndex, max 값을 설정해두고
  3. leftIndex가 rightIndex보다 커질 때까지 while문을 돌리고
  4. while문 안에서 leftIndex, rightIndex로 storeWater의 양을 구해 max값과 비교
  5. 높이가 더 작은 쪽의 index를 ++ (작은 쪽에서 ++을 해야 water의 max 값이 더 커질 수 있기 때문)
  • Runtime 60 ms, Memory 49.6 MB
profile
내일도 글쓰기

0개의 댓글