Skip to content

Commit 0b5cf91

Browse files
HouseRobber
1 parent bf45d70 commit 0b5cf91

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

EASY/src/easy/HouseRobber.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package easy;
2+
3+
/**198. House Robber
4+
5+
Total Accepted: 82030
6+
Total Submissions: 230179
7+
Difficulty: Easy
8+
9+
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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
10+
11+
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
12+
13+
Credits:
14+
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.*/
15+
public class HouseRobber {
16+
17+
//classical dp problem
18+
public int rob(int[] nums) {
19+
20+
if(nums == null || nums.length == 0) return 0;
21+
if(nums.length == 1) return nums[0];
22+
if(nums.length == 2) return Math.max(nums[0], nums[1]);
23+
int[] dp = new int[nums.length];
24+
dp[0] = nums[0];
25+
dp[1] = Math.max(nums[0], nums[1]);
26+
for(int i = 2; i < nums.length; i++){
27+
dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]);
28+
}
29+
return dp[nums.length-1];
30+
31+
}
32+
33+
}

0 commit comments

Comments
 (0)