Published:
Updated:

  • Reference
  • Hard ๋ฌธ์ œ๋ผ ๊ทธ๋Ÿฐ์ง€ ์ด ๊ธฐ๋ฒ•์„ ์ƒ๊ฐํ•ด ๋‚ด๊ธฐ ๊ฝค ๊นŒ๋‹ค๋กญ๋‹ค.
    • ์ตœ๋Œ€ ๋†’์ด๋Š” ์žฅ๋ฒฝ ์—ญํ• ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์„ ํ•ญ์ƒ ๊ธฐ์–ตํ•˜๊ณ  ์žˆ์ž!


Solution

from typing import List


class Solution:
    # ์ตœ๋Œ€ ๋†’์ด ๋ง‰๋Œ€๋Š” ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ์„ ๊ฐ€๋ฅด๋Š” ์žฅ๋ฒฝ ์—ญํ• ์„ ํ•จ
    def trap(self, height: List[int]) -> int:
        answer = 0
        lt, rt = 0, len(height) - 1
        lt_max, rt_max = 0, 0

        # ๊ฐ€์žฅ ๋†’์ด๊ฐ€ ๋†’์€ ๋ง‰๋Œ€์ธ, "์ตœ๋Œ€" ์ง€์ ์—์„œ ์ขŒ์šฐ ํฌ์ธํ„ฐ๊ฐ€ ์„œ๋กœ ๋งŒ๋‚˜๊ฒŒ ๋จ
        # ๋”ฑ ๊ทธ ์ „๊นŒ์ง€ ๋ฐ˜๋ณต๋ฌธ ๋Œ์•„์ฃผ๊ธฐ
        while lt < rt:
            lt_max, rt_max = max(height[lt], lt_max), max(height[rt], rt_max)

            # ์ขŒ์šฐ ์ •ํ•ด์ง„ ๊ฒƒ ์—†์ด, ๋‚ฎ์€ ์ชฝ์—์„œ ๋†’์€ ์ชฝ์„ ํ–ฅํ•ด ํฌ์ธํ„ฐ๊ฐ€ ๊ฐ€์šด๋ฐ๋กœ ์ ์  ์ด๋™ํ•จ
            # ์˜ค๋ฅธ์ชฝ์ด ํฌ๋ฉด, ์™ผ์ชฝ์ด ์ด๋™
            if lt_max < rt_max:
                answer += lt_max - height[lt]
                lt += 1
            # ์™ผ์ชฝ์ด ํฌ๋ฉด, ์˜ค๋ฅธ์ชฝ์ด ์ด๋™
            else:
                answer += rt_max - height[rt]
                rt -= 1

        return answer

Leave a comment