Skip to content

Commit 1b71a39

Browse files
committed
Solution for: House robber DP
1 parent 17df05f commit 1b71a39

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/leetcode/HouseRobber.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package leetcode;
2+
3+
public class HouseRobber {
4+
5+
public static void main(String[] args) {
6+
HouseRobber test = new HouseRobber();
7+
System.out.println(test.rob(new int[]{2,15,5,16}));
8+
9+
}
10+
11+
public int rob(int[] nums) {
12+
if(nums == null || nums.length ==0) return 0;
13+
int[] max = new int[nums.length];
14+
if(nums.length==1) return nums[0];
15+
if(nums.length==2) return Math.max(nums[0], nums[1]);
16+
max[0]= nums[0];
17+
max[1]= Math.max(nums[0], nums[1]);
18+
for(int i = 2; i< nums.length; i++){
19+
max[i]= Math.max(max[i-2]+nums[i], max[i-1]);
20+
}
21+
return max[nums.length-1];
22+
}
23+
24+
}

0 commit comments

Comments
 (0)