House Robber II
LeetCode 213 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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.