This approach uses a dynamic programming table, where we maintain an array 'dp' such that dp[i] represents the maximum amount of money that can be robbed up to house i. We iterate through the list of houses and for each house, decide whether to rob it or skip it, based on the previous results stored in the dp table.
Time Complexity: O(n) - We iterate through all houses once.
Space Complexity: O(n) - We use an additional array 'dp' to store intermediate results.
1using System;
2class Solution {
3 public int Rob(int[] nums) {
4 if (nums.Length == 0) return 0;
5 if (nums.Length == 1) return nums[0];
6
7 int[] dp = new int[nums.Length];
8 dp[0] = nums[0];
9 dp[1] = Math.Max(nums[0], nums[1]);
10
11 for (int i = 2; i < nums.Length; i++) {
12 dp[i] = Math.Max(dp[i-1], dp[i-2] + nums[i]);
13 }
14 return dp[nums.Length-1];
15 }
16
17 static void Main() {
18 int[] nums = {2, 7, 9, 3, 1};
19 Solution sol = new Solution();
20 Console.WriteLine("Max amount that can be robbed: " + sol.Rob(nums));
21 }
22}
This C# solution uses a dp array where each index keeps a tally of the maximum profit obtainable up that point. Each iteration chooses the more profitable option between robbing or skipping a house.
This approach optimizes the space complexity by not using a separate array for storing results of subproblems. Instead, we use two variables to keep track of the maximum amount that can be robbed up to the last two houses considered. This eliminates the need for an auxiliary array and reduces space complexity to O(1).
Time Complexity: O(n) - Elements from the house array are each visited once.
Space Complexity: O(1) - Only a few extra variables are used for keeping track.
1using System;
2class Solution {
3 public int Rob(int[] nums) {
4 if (nums.Length == 0) return 0;
5 if (nums.Length == 1) return nums[0];
6
7 int prev1 = 0, prev2 = 0, current = 0;
8
9 foreach (var num in nums) {
10 int temp = prev1;
11 prev1 = Math.Max(prev2 + num, prev1);
12 prev2 = temp;
13 }
14 return prev1;
15 }
16
17 static void Main() {
18 int[] nums = {2, 7, 9, 3, 1};
19 Solution sol = new Solution();
20 Console.WriteLine("Max amount that can be robbed: " + sol.Rob(nums));
21 }
22}
In the C# code, tracking with only two keeping track of the last two non-adjacent sums using prev1 and prev2. This iteration computes a decision at each point using these two elements.