?? Problem-Solving w/ DP: House Robber (LeetCode) ??
Problem description: https://leetcode.com/problems/house-robber/
How to maximize your loot without triggering alarms? That’s the gist of the House Robber problem on LeetCode. Here's the challenge:
You’re a professional robber planning to rob houses on a street ???♂?. Each house has a stash of cash, but the catch is that you can’t rob two adjacent houses—their security systems are linked. The goal? Figure out the maximum amount you can rob without getting caught. ??
?? My Solution:
To crack this, I used a dynamic programming approach:
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1: return nums[0]
nums[1] = max(nums[1], nums[0])
for i in range(2, len(nums)):
nums[i] = max(nums[i-1], nums[i] + nums[i-2])
return nums[len(nums) - 1]
Key Insights:
1?? If there’s only one house, rob it—no brainer!
领英推荐
2?? Update each house’s value to the maximum loot possible up to that point.
3?? For every house starting from the 3rd, you decide to:
This greedy yet calculated approach ensures you squeeze out every last dollar without tripping alarms! ??
For example:
? Why I Love This Problem: It’s a classic mix of logic and optimization that reflects real-world decision-making (though hopefully not for actual robbing ??).