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.