File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int rob (int [] nums ) {
3+ // Dynamic Planning
4+ // Time Complexity: O(n)
5+ // Space Complexity: O(n) for the dp array
6+ // When applying DP, it is important to define the accumulated state clearly.
7+
8+ if (nums .length == 1 ) {
9+ return nums [0 ];
10+ }
11+
12+ // The state of dp is maximum amount of robbery at i
13+ int [] dp = new int [nums .length ];
14+
15+ dp [0 ] = nums [0 ];
16+ dp [1 ] = Math .max (nums [0 ], nums [1 ]);
17+
18+ for (int i = 2 ; i < nums .length ; i ++) {
19+ dp [i ] = Math .max (
20+ // If we skip the current house,
21+ // we can take the maximum amount of robbery at i - 1
22+ dp [i - 1 ],
23+ // If we rob the current house, we cannot rob the previous house
24+ // so we can take the maximum amount of robbery at i - 2
25+ dp [i - 2 ] + nums [i ]);
26+ }
27+
28+ return dp [nums .length - 1 ];
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments