Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 213 · 1D / Fibonacci

House Robber II

LeetCode 213 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).

நடுத்தரம்ArrayDynamic Programming
LeetCode இல் திற ↗

நான் House Robber II (LeetCode 213) ஐ இப்படித் தீர்த்தேன் — 1D / Fibonacci பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

The houses form a circle, so the first and last are neighbours and can never both be robbed. Break the circle by solving the straight-line House Robber twice: once without the first house and once without the last, and keep the better result.

Approach

  1. 1

    Reuse the linear House Robber DP as rob_all(nums).

  2. 2

    Case A: drop the first house — the last house is now free to take.

  3. 3

    Case B: drop the last house — the first house is now free to take.

  4. 4

    Return the larger of the two; a single house is returned directly.

நான் எப்படித் தீர்த்தேன்

Two linear passesPythonO(n) time · O(n) space
class Solution:
    def rob_all(self, nums: List[int]) -> int:
        #eithter i can rob and go to index-2
        #or skip and go to index-1
        if len(nums)==1:
            return nums[0]
        n = len(nums)
        dp=[float("-inf")]*n
        dp[0]=nums[0]
        dp[1]=max(nums[0],nums[1])
        for index in range(2,n):
            rob = nums[index]+dp[index-2]
            dontrob = dp[index-1]
            dp[index]=max(rob,dontrob)
        return dp[n-1]
    def rob(self, nums: List[int]) -> int:
        if len(nums)==1:
            return nums[0]
        #skip first or skip last since they are adjacent and get max for these two options
        return max(self.rob_all(nums[1:]),self.rob_all(nums[:len(nums)-1]))
        
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

House Robber II — அடிக்கடி கேட்கப்படும் கேள்விகள்

House Robber II பின்னாலுள்ள intuition என்ன?

The houses form a circle, so the first and last are neighbours and can never both be robbed. Break the circle by solving the straight-line House Robber twice: once without the first house and once without the last, and keep the better result.

House Robber II (LeetCode 213) ஐ எப்படித் தீர்ப்பது?

1. Reuse the linear House Robber DP as rob_all(nums). 2. Case A: drop the first house — the last house is now free to take. 3. Case B: drop the last house — the first house is now free to take. 4. Return the larger of the two; a single house is returned directly.

House Robber II இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(n). (Accepted approach: Two linear passes.)

House Robber II இல் பொதுவான தவறுகள் என்ன?

With one house, slicing both ends would leave nothing — handle len == 1 first. Don't try to track 'was the first house robbed' inside one pass; two passes is simpler and safe.