Skip to content

Commit 2eaa83a

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 198_House_Robber.java
1 parent c2e75c0 commit 2eaa83a

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

Dynamic Programming/198_House_Robber.java

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

7-
int[] memo = new int[nums.length + 1];
7+
int[] memo = new int[nums.length];
88
Arrays.fill(memo, -1);
9-
return robHouses(nums, nums.length - 1, memo);
9+
return helper(nums, 0, memo);
1010
}
1111

12-
private int robHouses(int[] houses, int houseNo, int[] memo) {
13-
if (houseNo < 0) {
12+
private int helper(int[] nums, int idx, int[] memo) {
13+
if (idx >= nums.length) {
1414
return 0;
1515
}
16-
if (memo[houseNo] >= 0) {
17-
return memo[houseNo];
16+
17+
if (memo[idx] != -1) {
18+
return memo[idx];
1819
}
1920

20-
int result = Math.max(robHouses(houses, houseNo - 2, memo) + houses[houseNo],
21-
robHouses(houses, houseNo - 1, memo));
22-
memo[houseNo] = result;
21+
int result = Math.max(helper(nums, idx + 1, memo), helper(nums, idx + 2, memo) + nums[idx]);
22+
23+
memo[idx] = result;
2324
return result;
2425
}
2526
}

0 commit comments

Comments
 (0)