File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ time: O(N)
3+ time: O(1)
4+ */
5+ class Solution {
6+
7+ public int rob (int [] nums ) {
8+ if (nums .length == 0 ) {
9+ return 0 ;
10+ }
11+ if (nums .length == 1 ) {
12+ return nums [0 ];
13+ }
14+
15+ return Math .max (
16+ dp (nums , 0 , nums .length - 2 ),
17+ dp (nums , 1 , nums .length - 1 )
18+ );
19+ }
20+
21+ private static int dp (int [] nums , int start , int end ) {
22+ int maxOfOneStepAhead = nums [end ];
23+ int maxOfTwoStepsAhead = 0 ;
24+
25+ for (int i = end - 1 ; i >= start ; --i ) {
26+ int curr = Math .max (maxOfOneStepAhead , maxOfTwoStepsAhead + nums [i ]);
27+
28+ maxOfTwoStepsAhead = maxOfOneStepAhead ;
29+ maxOfOneStepAhead = curr ;
30+ }
31+ return maxOfOneStepAhead ;
32+ }
33+ }
Original file line number Diff line number Diff line change 1+ /*
2+ time: O(N)
3+ space: O(1)
4+ */
5+ class Solution {
6+
7+ public int rob (int [] nums ) {
8+ if (nums .length == 0 ) {
9+ return 0 ;
10+ }
11+
12+ int maxOfTwoStepsAhead = 0 ;
13+ int maxOfOneStepAhead = nums [nums .length - 1 ];
14+
15+ for (int i = nums .length - 2 ; i >= 0 ; --i ) {
16+ int curr = Math .max (maxOfOneStepAhead , maxOfTwoStepsAhead + nums [i ]);
17+
18+ maxOfTwoStepsAhead = maxOfOneStepAhead ;
19+ maxOfOneStepAhead = curr ;
20+ }
21+ return maxOfOneStepAhead ;
22+ }
23+ }
You can’t perform that action at this time.
0 commit comments