Skip to content

Commit 510fb43

Browse files
committed
solve 198.house-robber
1 parent 91e648e commit 510fb43

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

vscode/198.house-robber.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* @lc app=leetcode id=198 lang=java
3+
*
4+
* [198] House Robber
5+
*
6+
* https://leetcode.com/problems/house-robber/description/
7+
*
8+
* algorithms
9+
* Easy (40.78%)
10+
* Total Accepted: 308.4K
11+
* Total Submissions: 754.1K
12+
* Testcase Example: '[1,2,3,1]'
13+
*
14+
* You are a professional robber planning to rob houses along a street. Each
15+
* house has a certain amount of money stashed, the only constraint stopping
16+
* you from robbing each of them is that adjacent houses have security system
17+
* connected and it will automatically contact the police if two adjacent
18+
* houses were broken into on the same night.
19+
*
20+
* Given a list of non-negative integers representing the amount of money of
21+
* each house, determine the maximum amount of money you can rob tonight
22+
* without alerting the police.
23+
*
24+
* Example 1:
25+
*
26+
*
27+
* Input: [1,2,3,1]
28+
* Output: 4
29+
* Explanation: Rob house 1 (money = 1) and then rob house 3 (money =
30+
* 3).
31+
* Total amount you can rob = 1 + 3 = 4.
32+
*
33+
* Example 2:
34+
*
35+
*
36+
* Input: [2,7,9,3,1]
37+
* Output: 12
38+
* Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house
39+
* 5 (money = 1).
40+
* Total amount you can rob = 2 + 9 + 1 = 12.
41+
*
42+
*
43+
*/
44+
class Solution {
45+
public int rob(int[] nums) {
46+
if (nums == null || nums.length == 0) return 0;
47+
48+
int n = nums.length;
49+
if (n == 1) return nums[0];
50+
51+
int[] dp = new int[n];
52+
dp[0] = nums[0];
53+
dp[1] = Math.max(nums[0], nums[1]);
54+
55+
for (int i = 2; i < n; i++) {
56+
dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]);
57+
}
58+
59+
return dp[n-1];
60+
}
61+
}
62+

0 commit comments

Comments
 (0)