House Robber Problem Solution in Java with Dynamic Programming

🚀 #100DaysOfCode – Day 16 Today’s focus: House Robber Problem (Dynamic Programming) 🏠💰 At first glance, the problem feels simple — just pick non-adjacent houses to maximize money. But the real challenge is choosing the optimal combination, not just alternating elements. 🔴 Brute Force Approach Try every possible combination of robbing or skipping houses. class Solution { public int rob(int[] nums) { return helper(nums, 0); } private int helper(int[] nums, int i) { if (i >= nums.length) return 0; int pick = nums[i] + helper(nums, i + 2); int notPick = helper(nums, i + 1); return Math.max(pick, notPick); } } ⛔ Time Complexity: O(2^n) (Exponential) 👉 Not efficient for large inputs 🟢 Optimized Approach (Dynamic Programming) Instead of recalculating, store previous results and build the solution. class Solution { public int rob(int[] nums) { int prev2 = 0; int prev1 = nums[0]; for (int i = 1; i < nums.length; i++) { int pick = nums[i] + prev2; int notPick = prev1; int curr = Math.max(pick, notPick); prev2 = prev1; prev1 = curr; } return prev1; } } ✅ Time Complexity: O(n) ✅ Space Complexity: O(1) 🧠 Key Insight At every house, you have two choices: Rob it → add value + skip previous house Skip it → take previous maximum 👉 dp[i] = max(nums[i] + dp[i-2], dp[i-1]) 💡 Learning of the Day Dynamic Programming is all about: Breaking problems into smaller subproblems Storing results to avoid recomputation Making optimal decisions at each step #Day16 #100DaysOfCode #DSA #Java #DynamicProgramming #CodingJourney #LeetCode #ProblemSolving

To view or add a comment, sign in

Explore content categories