File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ // * can't rob two adj houses in the same night
3+ // * return: max amount of money robbale in one night
4+ public int rob (int [] nums ) {
5+ if (nums .length == 1 ) return nums [0 ];
6+ if (nums .length == 2 ) return Math .max (nums [0 ], nums [1 ]);
7+
8+ // maxSum[i] = max sum possible at i (inclusive)
9+ int [] maxSum = new int [nums .length ];
10+ maxSum [0 ] = nums [0 ];
11+ maxSum [1 ] = nums [1 ];
12+
13+ for (int i = 2 ; i < nums .length ; i ++) {
14+ if (i == 2 ) {
15+ maxSum [i ] = nums [i ] + maxSum [i -2 ];
16+ continue ;
17+ }
18+
19+ // adj houses(i-1) can't be robbed
20+ // choices are:
21+ // 1. i-2 th house (choosing without skipping a house)
22+ // 2. i-3 th house (choosing with skipping a house)
23+ // * choosing < i-4 th houses wouldn't be optimal because it'll be missing either of 1. or 2.
24+ maxSum [i ] = nums [i ] + Math .max (maxSum [i -2 ], maxSum [i -3 ]);
25+ }
26+
27+ return Math .max (maxSum [nums .length -2 ], maxSum [nums .length -1 ]);
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments