Coding Interview

[LeetCode] DP - 42. Trapping Rain Water

milliwonkim 2022. 10. 1. 16:56
반응형
SMALL

문제

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

 

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

 

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

코드

투포인터

/**
 * @param {number[]} height
 * @return {number}
 */
function trap(height) {
  if (height == null || height.length === 0) return 0;

  let l = 0;
  let r = height.length - 1;

  let lMax = 0;
  let rMax = 0;

  let res = 0;

  while (l < r) {
    lMax = Math.max(lMax, height[l]);
    if (height[l] < lMax) {
      res += lMax - height[l];
    }

    rMax = Math.max(rMax, height[r]);
    if (height[r] < rMax) {
      res += rMax - height[r];
    }

    height[l] < height[r] ? l++ : r--;
  }

  return res;
}

 

DP 풀이(시간초과)

/**
 * @param {number[]} height
 * @return {number}
 */
function trap(height) {
  if (height == null || height.length === 0) return 0;

  let res = 0;
  let l = height.length;
  let lMax = {};
  let rMax = {};

  lMax[0] = height[0];
  
  // 왼쪽 기준으로 최댓값
  for (let i = 1; i < l; i++) {
    lMax[i] = Math.max(height[i], lMax[i - 1]);
  }

  // 오른쪽 기준으로 최댓값
  rMax[l - 1] = height[l - 1];
  for (let i = l - 2; i >= 0; i--) {
    rMax[i] = Math.max(height[i], rMax[i + 1]);
  }

  // 왼쪽 오른쪽 최댓값들 중 최솟값을 현재 위치의 height와 빼기
  for (let i = 0; i < height.length; i++) {
      console.log(lMax[i], rMax[i], height[i])
    res += Math.min(lMax[i], rMax[i]) - height[i];
  }

  return res;
}

 

 

반응형
LIST