House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array `nums` representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Examples
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 400
Dynamic Programming (Space Optimized)
Approach
For each house `i`, we have two choices: rob it or skip it. If we rob it, we add its money to the maximum money we could rob from houses up to `i-2`. If we skip it, we take the maximum money we could rob from houses up to `i-1`. So, the DP recurrence is: `dp[i] = max(dp[i-1], dp[i-2] + nums[i])`. Since we only need the last two values (`dp[i-1]` and `dp[i-2]`), we can optimize space by using just two variables instead of a full array.
Complexity Analysis
Time complexity is O(n) as we iterate through the array once. Space complexity is O(1) since we only use two variables for tracking state.
class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) return 0; if (nums.length == 1) return nums[0]; int rob1 = 0; // max money up to i-2 int rob2 = 0; // max money up to i-1 for (int num : nums) { // max(rob current house + money up to i-2, skip current house) int temp = Math.max(num + rob1, rob2); rob1 = rob2; rob2 = temp; } return rob2; }}