File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ // DP
4
+ public int rob (int [] nums ) {
5
+ int n = nums .length ;
6
+
7
+ if (n == 0 ) {
8
+ return 0 ;
9
+ }
10
+
11
+ if (n == 1 ) {
12
+ return nums [0 ];
13
+ }
14
+
15
+ int notRobbingLast = robHouses (nums , 0 , n - 2 );
16
+ int notRobbingFirst = robHouses (nums , 1 , n - 1 );
17
+
18
+ return Math .max (notRobbingLast , notRobbingFirst );
19
+ }
20
+
21
+ private int robHouses (int [] nums , int start , int end ) {
22
+
23
+ int length = end - start + 1 ;
24
+
25
+ if (length == 0 ) {
26
+ return 0 ;
27
+ }
28
+
29
+ if (length == 1 ) {
30
+ return nums [start ];
31
+ }
32
+
33
+ int [] dp = new int [length ];
34
+
35
+ dp [0 ] = nums [start ];
36
+ dp [1 ] = Math .max (nums [start ], nums [start + 1 ]);
37
+
38
+ for (int i = 2 ; i < length ; i ++) {
39
+ dp [i ] = Math .max (dp [i - 2 ] + nums [start + i ], dp [i - 1 ]);
40
+ }
41
+
42
+ return dp [length - 1 ];
43
+ }
44
+ }
45
+
You can’t perform that action at this time.
0 commit comments