File tree Expand file tree Collapse file tree 1 file changed +21
-14
lines changed
Expand file tree Collapse file tree 1 file changed +21
-14
lines changed Original file line number Diff line number Diff line change 1- /*
2- Problem: https://leetcode.com/problems/house-robber/
3- Description: the maximum amount of money you can rob if you cannot rob two adjacent houses
4- Concept: Array, Dynamic Programming
5- Time Complexity: O(n), Runtime: 0ms
6- Space Complexity: O(1), Memory: 41.42MB
7- */
1+ /**
2+ * <a href="https://leetcode.com/problems/house-robber/">week01-5.house-robber</a>
3+ * <li> Description: the maximum amount of money you can rob if you cannot rob two adjacent houses </li>
4+ * <li> Concept: Array, Dynamic Programming </li>
5+ * <li> Time Complexity: O(n), Runtime: 0ms </li>
6+ * <li> Space Complexity: O(1), Memory: 41.1MB </li>
7+ */
8+
89class Solution {
910 public int rob (int [] nums ) {
10- int sum1 = nums [0 ];
11- int sum2 = nums .length >1 ? Math .max (nums [0 ], nums [1 ]) : nums [0 ];
12- for (int i =2 ; i <nums .length ; i ++){
13- int sum3 =Math .max (nums [i ]+sum1 ,sum2 );
14- sum1 =sum2 ;
15- sum2 =sum3 ;
11+ if (nums .length ==1 ) {
12+ return nums [0 ];
1613 }
17- return sum2 ;
14+
15+ List <Integer > money = new ArrayList <>();
16+ money .add (nums [0 ]);
17+ money .add (Math .max (nums [0 ], nums [1 ]));
18+
19+ for (int i =2 ; i <nums .length ; i ++) {
20+ money .set (0 , Math .max (money .get (0 )+nums [i ], money .get (1 )));
21+ Collections .swap (money , 0 , 1 );
22+ }
23+
24+ return money .get (1 );
1825 }
1926}
You can’t perform that action at this time.
0 commit comments