Skip to content

Commit d67d4fb

Browse files
Sean PrashadSean Prashad
Sean Prashad
authored and
Sean Prashad
committed
Update 198_House_Robber.java
1 parent d895f6f commit d67d4fb

File tree

1 file changed

+6
-15
lines changed

1 file changed

+6
-15
lines changed

Dynamic Programming/198_House_Robber.java

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,14 @@ public int rob(int[] nums) {
44
return 0;
55
}
66

7-
int[] memo = new int[nums.length];
8-
Arrays.fill(memo, -1);
9-
return helper(nums, 0, memo);
10-
}
7+
int currHouse = 0, oneHouseAgo = 0, twoHousesAgo = 0;
118

12-
private int helper(int[] nums, int idx, int[] memo) {
13-
if (idx >= nums.length) {
14-
return 0;
9+
for (int i = 0; i < nums.length; i++) {
10+
currHouse = Math.max(twoHousesAgo + nums[i], oneHouseAgo);
11+
twoHousesAgo = oneHouseAgo;
12+
oneHouseAgo = currHouse;
1513
}
1614

17-
if (memo[idx] != -1) {
18-
return memo[idx];
19-
}
20-
21-
int result = Math.max(helper(nums, idx + 1, memo), helper(nums, idx + 2, memo) + nums[idx]);
22-
23-
memo[idx] = result;
24-
return result;
15+
return currHouse;
2516
}
2617
}

0 commit comments

Comments
 (0)