반응형
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
'Coding Interview' 카테고리의 다른 글
[LeetCode] DP - 53. Maximum Subarray (0) | 2022.10.01 |
---|---|
알고리즘 유형을 알아보자 (0) | 2022.10.01 |
[LeetCode] BFS - 102. Binary Tree Level Order Traversal (0) | 2022.09.30 |
[기타] 코딩테스트에 활용되는 수학 이론 (1) | 2022.09.30 |
[LeetCode] DP - 279. Perfect Squares (feat. 라그랑주의 네제곱수) (0) | 2022.09.30 |