File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments