We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 640cd98 commit eb1a80cCopy full SHA for eb1a80c
Medium/House Robber.java
@@ -1,14 +1,11 @@
1
class Solution {
2
- public int rob(int[] nums) {
3
- if (nums.length == 1) {
4
- return nums[0];
+ public int rob(int[] nums) {
+ int n = nums.length;
+ int[] dp = new int[n + 1];
5
+ dp[1] = nums[0];
6
+ for (int i = 1; i < n; i++) {
7
+ dp[i + 1] = Math.max(dp[i], dp[i - 1] + nums[i]);
8
+ }
9
+ return dp[n];
10
}
- int[] dp = new int[nums.length];
- dp[0] = nums[0];
- dp[1] = Math.max(nums[0], nums[1]);
- for (int i = 2; i < nums.length; i++) {
- dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
11
- }
12
- return dp[nums.length - 1];
13
14
0 commit comments