Skip to content

Commit ceaa963

Browse files
committed
add: NeighborhoodBurglary
1 parent 1d5bf98 commit ceaa963

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class NeighborhoodBurglary {
2+
public int neighborhoodBurglary(int[] houses) {
3+
// Handle the cases when the array is less than the size of 2 to
4+
// avoid out-of-bounds errors when assigning the base case values.
5+
if (houses == null || houses.length == 0) {
6+
return 0;
7+
}
8+
if (houses.length == 1) {
9+
return houses[0];
10+
}
11+
int[] dp = new int[houses.length];
12+
// Base case: when there's only one house, rob that house.
13+
dp[0] = houses[0];
14+
// Base case: when there are two houses, rob the one with the most
15+
// money.
16+
dp[1] = Math.max(houses[0], houses[1]);
17+
// Fill in the rest of the DP array.
18+
for (int i = 2; i < houses.length; i++) {
19+
// 'dp[i]' = max(profit if we skip house 'i', profit if we rob
20+
// house 'i').
21+
dp[i] = Math.max(dp[i - 1], houses[i] + dp[i - 2]);
22+
}
23+
return dp[houses.length - 1];
24+
}
25+
}

0 commit comments

Comments
 (0)