๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 42 - Trapping Rain Water (Hard)

by HandHand 2023. 4. 30.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 42๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

์›…๋ฉ์ด๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹จ์กฐ๊ฐ์†Œ ๊ตฌ๊ฐ„์„ ์•Œ์•„์•ผํ•ฉ๋‹ˆ๋‹ค.

O(n) ์— ์ด๋ฅผ ์•Œ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ๋ฌด์—‡์ผ๊นŒ์š”?

 

์ด๋ฅผ ์œ„ํ•ด monotonic stack์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

height ์˜ ์ธ๋ฑ์Šค๋ฅผ i ๋ผ๊ณ  ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

(a) height[i] ๊ฐ€ stack top ๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๊ทธ๋ƒฅ push ํ•ฉ๋‹ˆ๋‹ค.
(b) stack top ๊ฐ’๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๋‹ค๋ฉด push ํ•˜๊ธฐ์ „์— stack ์—์„œ height[i] ๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ๊ฐ’์„ ๊ฐ€์ง€๋Š” ์š”์†Œ๋“ค์„ ๋ชจ๋‘ pop ํ•ฉ๋‹ˆ๋‹ค.

 

๋ฌผ ์›…๋ฉ์ด์˜ ํฌ๊ธฐ๋ฅผ ์•Œ๋ ค๋ฉด ๋†’์ด * ๋„ˆ๋น„ ๋ฅผ ์•Œ์•„์•ผํ•ฉ๋‹ˆ๋‹ค.

๋„ˆ๋น„๋Š” index ๊ฐ’์œผ๋กœ ์‰ฝ๊ฒŒ ์•Œ ์ˆ˜ ์žˆ๊ณ , ๋†’์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

min(height[stack[top-1]], height[i]) - height[stack[top]]

 

ํ•„์š”ํ•œ ๊ฐ’๋“ค์„ ์•Œ์•˜์œผ๋‹ˆ, ์ด์ œ ์œ„ ๊ณผ์ •๋“ค์„ ๋ฐฐ์—ด์˜ ๋์— ๋„๋‹ฌํ• ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ด์ค๋‹ˆ๋‹ค.

 

๐Ÿ‘จ‍๐Ÿ’ป ์ฝ”๋“œ

/**
 * @param {number[]} heights
 * @return {number}
 */
var trap = function(heights) {
    let answer = 0

    const stack = []

    for (let idx = 0; idx < heights.length; idx += 1) {
        if (stack.length <= 0 || heights[stack.at(-1)] > heights[idx]) {
            stack.push(idx)
            continue
        }

        while (stack.length > 0 && heights[stack.at(-1)] <= heights[idx]) {
            const top = stack.at(-1)
            stack.pop()

            if (stack.length <= 0) {
                break
            }

            const width = idx - stack.at(-1) - 1
            const height = Math.min(heights[stack.at(-1)], heights[idx]) - heights[top]

            answer += (width * height)
        }

        stack.push(idx)
    }

    return answer
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€