Skip to content

Commit 01117d7

Browse files
committed
Add house robber solution
1 parent 8fb11ee commit 01117d7

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package java1.algorithms.dynamicProgramming;
2+
3+
public class HouseRobber {
4+
// TC:O(n) SC:O(1)
5+
private static int robber1(int[] nums) {
6+
int rob1 = nums[0], rob2 = Math.max(rob1, nums[1]);
7+
for(int i=2; i< nums.length; i++) {
8+
int temp = Math.max(nums[i]+rob1, rob2);
9+
rob1 = rob2;
10+
rob2 = temp;
11+
}
12+
return rob2;
13+
}
14+
15+
// TC:O(n) SC:O(n)
16+
private static int robber2(int[] nums) {
17+
int[] dp = new int[nums.length];
18+
dp[0] = nums[0];
19+
dp[1] = nums[1];
20+
for(int i=2; i<nums.length; i++) {
21+
dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]);
22+
}
23+
return dp[nums.length-1];
24+
}
25+
26+
public static void main(String[] args) {
27+
int[] nums = {2,7,9,3,1};
28+
System.out.println(robber1(nums));
29+
System.out.println(robber2(nums));
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// TC:O(n) SC:O(1)
2+
function robber1(nums) {
3+
let rob1 = nums[0], rob2 = nums[1];
4+
5+
for(let i=2; i<nums.length; i++) {
6+
let temp = Math.max(nums[i] + rob1, rob2);
7+
rob1 = rob2;
8+
rob2 = temp;
9+
}
10+
return rob2;
11+
}
12+
13+
// TC:O(n) SC:O(n)
14+
function robber2(nums) {
15+
let dp = new Array(nums.length).fill(0);
16+
dp[0] = nums[0];
17+
dp[1] = nums[1];
18+
19+
for(let i=2; i< nums.length; i++) {
20+
dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]);
21+
}
22+
return dp[nums.length-1];
23+
}
24+
25+
let nums = [2,7,9,3,1];
26+
console.log(robber1(nums));
27+
console.log(robber2(nums));

0 commit comments

Comments
 (0)