Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 213 · 1D / Fibonacci

House Robber II

LeetCode 213 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

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

मध्यमArrayDynamic Programming

मी 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.