Skip to content

Commit e2a125b

Browse files
committed
add: NeighborhoodBurglaryOptimized
1 parent ceaa963 commit e2a125b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class NeighborhoodBurglaryOptimized {
2+
public int neighborhoodBurglaryOptimized(int[] houses) {
3+
if (houses == null || houses.length == 0) {
4+
return 0;
5+
}
6+
if (houses.length == 1) {
7+
return houses[0];
8+
}
9+
// Initialize the variables with the base cases.
10+
int prevMaxProfit = Math.max(houses[0], houses[1]);
11+
int prevPrevMaxProfit = houses[0];
12+
13+
for (int i = 2; i < houses.length; i++) {
14+
int currMaxProfit = Math.max(prevMaxProfit, houses[i] + prevPrevMaxProfit);
15+
// Update the values for the next iteration.
16+
prevPrevMaxProfit = prevMaxProfit;
17+
prevMaxProfit = currMaxProfit;
18+
}
19+
return prevMaxProfit;
20+
}
21+
}

0 commit comments

Comments
 (0)