leetcode [11]

Seungwon·2023년 5월 8일

leetcode

목록 보기
7/7

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.

A와 B 사이의 면적을 구하는데, A와 B중 낮은 값를 세로 값으로 생각한다. A인덱스와 B인덱스의 차를 가로 값으로 생각한다.

가로 세로를 곱했을때 가장 면적이 클 수 있는 값을 찾는 루프를 만들어야 하는데, 이전에 했던 문제들과 비슷하다

투 포인터를 이용해서 A와 B중 낮은 값를 B인덱스-A인덱스한 값에 곱해서 맥스값으로 저장하면 된다.

맥스값을 찾는게 목적이기 때문에, A와 B 인덱스중 낮은 값의 포인터를 움직여 준다.
(left가 작으면 left를 ++, right가 작으면 right를 --)

var maxArea = function(height) {
  let maxArea = 0;
  let l = 0;
  let r = height.length - 1;

  while (l < r) {
    
    const area = Math.min(height[l], height[r]) * (r - l);
    maxArea = Math.max(maxArea, area);
    console.log('left :' + l);
    console.log('right :' + r);
    console.log('area :' + area);
    console.log('-');
    if (height[l] < height[r]) {
      l++;
    } else {
      r--;
    }
    
  }

  return maxArea;

};

left :0
right :8
area :8
-
left :1
right :8
area :49
-
left :1
right :7
area :18
-
left :1
right :6
area :40
-
left :1
right :5
area :16
-
left :1
right :4
area :15
-
left :1
right :3
area :4
-
left :1
right :2
area :6
-

0개의 댓글