File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ # O(n) time, O(n) space
2
+
3
+ class Solution :
4
+ def rob (self , nums : List [int ]) -> int :
5
+ if not nums : return 0
6
+ if len (nums ) == 1 : return nums [0 ]
7
+
8
+ dp = [0 ] * len (nums )
9
+ dp [0 ] = nums [0 ]
10
+ dp [1 ] = max (nums [0 ], nums [1 ])
11
+
12
+ for i in range (2 , len (nums )):
13
+ dp [i ] = max (dp [i - 1 ], nums [i ] + dp [i - 2 ])
14
+
15
+ return dp [- 1 ]
16
+
17
+
18
+ # TS 코드
19
+ # function rob(nums: number[]): number {
20
+ # if (nums.length === 0) return 0;
21
+ # if (nums.length === 1) return nums[0];
22
+
23
+ # const dp: number[] = new Array(nums.length).fill(0);
24
+ # dp[0] = nums[0];
25
+ # dp[1] = Math.max(nums[0], nums[1]);
26
+
27
+ # for (let i = 2; i < nums.length; i++) {
28
+ # dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
29
+ # }
30
+
31
+ # return dp[nums.length - 1];
32
+ # }
You can’t perform that action at this time.
0 commit comments