1
- public class Solution {
2
- public static int rob (int [] nums ) {
3
-
4
- if (nums == null || nums .length == 0 ) {
5
- return 0 ;
6
- }
7
-
8
- if (nums .length == 1 ) {
9
- return nums [0 ];
10
- }
11
-
12
- if (nums .length == 2 ) {
13
- return Math .max (nums [0 ], nums [1 ]);
14
- }
15
-
16
- return Math .max (help (Arrays .copyOfRange (nums , 0 , nums .length - 1 )),
17
- help (Arrays .copyOfRange (nums , 1 , nums .length )));
18
- }
19
-
20
- public static int help (int [] nums ) {
21
-
22
- if (nums .length == 0 ) {
23
- return 0 ;
24
- }
25
-
26
- if (nums .length == 1 ) {
27
- return nums [0 ];
28
- }
29
-
30
- int [] P = new int [nums .length ];
31
-
32
- P [0 ] = nums [0 ];
33
- P [1 ] = Math .max (nums [0 ], nums [1 ]);
34
-
35
- for (int i = 2 ; i < nums .length ; i ++) {
36
- P [i ] = Math .max (nums [i ] + P [i - 2 ], P [i - 1 ]);
37
- }
38
-
39
- return P [nums .length - 1 ];
40
- }
1
+ class Solution {
2
+ public int rob (int [] nums ) {
3
+ int n = nums .length ;
4
+ if (n == 1 ) {
5
+ return nums [0 ];
6
+ }
7
+ int sub1 = robInternal (Arrays .copyOfRange (nums , 0 , n - 1 ));
8
+ int sub2 = robInternal (Arrays .copyOfRange (nums , 1 , n ));
9
+ return Math .max (sub1 , sub2 );
10
+ }
11
+
12
+ private int robInternal (int [] nums ) {
13
+ int n ;
14
+ if ((n = nums .length ) == 0 ) {
15
+ return 0 ;
16
+ }
17
+ if (n == 1 ) {
18
+ return nums [0 ];
19
+ }
20
+ int pre = nums [0 ];
21
+ int cur = Math .max (nums [0 ], nums [1 ]);
22
+ for (int i = 2 ; i < n ; ++i ) {
23
+ int t = Math .max (pre + nums [i ], cur );
24
+ pre = cur ;
25
+ cur = t ;
26
+ }
27
+ return cur ;
28
+ }
41
29
}
0 commit comments