Skip to content

Commit 817145c

Browse files
committed
add solution of house-robber
1 parent ed15db0 commit 817145c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

house-robber/jinhyungrhee.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.*;
2+
class Solution {
3+
4+
// dfs with memoization => O(N)
5+
public int rob(int[] nums) {
6+
Map<Integer,Integer> memo = new HashMap<>();
7+
return dfs(0, nums, memo);
8+
}
9+
10+
public int dfs(int start, int[] nums, Map<Integer, Integer> memo) {
11+
if (memo.containsKey(start)) return memo.get(start);
12+
if (start >= nums.length) {
13+
memo.put(start, 0);
14+
} else {
15+
memo.put(start, Math.max(
16+
nums[start] + dfs(start + 2, nums, memo),
17+
dfs(start + 1, nums, memo))
18+
);
19+
}
20+
return memo.get(start);
21+
}
22+
}

0 commit comments

Comments
 (0)