-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathEgonD3V.py
60 lines (47 loc) ยท 1.96 KB
/
EgonD3V.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from collections import deque
from typing import List
from unittest import TestCase, main
class Solution:
def rob(self, nums: List[int]) -> int:
return self.solve_dp(nums)
"""
Runtime: 0 ms (Beats 100.00%)
Time Complexity: O(n)
- ์ธ๋ฑ์ค๊ฐ 0์ธ ๊ณณ์ ๋๋์งํ ๊ฒฝ์ฐ์ ๋ํ dp1์์, ์ธ๋ฑ์ค 2๋ถํฐ n-2๊น์ง ์กฐํํ๋ฏ๋ก O(n - 3)
- ๊ฐ ์กฐํ๋ง๋ค 2ํญ max ์ฐ์ฐ์ 2ํ์ฉ ํ๋ฏ๋ก * O(2 * 2)
- ์ธ๋ฑ์ค๊ฐ 0์ธ ๊ณณ์ ๋๋์งํ์ง ์๋ ๊ฒฝ์ฐ์ ๋ํ dp2์์, ์ธ๋ฑ์ค 2๋ถํฐ n-1๊น์ง ์กฐํํ๋ฏ๋ก O(n - 2)
- ๊ฐ ์กฐํ๋ง๋ค 2ํญ max ์ฐ์ฐ์ 2ํ์ฉ ํ๋ฏ๋ก * O(2 * 2)
- ๊ทธ ์ธ์ ์ ํด์ง ํ์์ max ์ฐ์ฐ๋ค์ ๋ฌด์, O(C)
> O(n - 3) * O(2 * 2) + O(n - 4) * O(2 * 2) + O(C) ~= O(n) * O(4) ~= O(n)
Memory: 16.59 (Beats 62.16%)
Space Complexity: O(n)
- dp1๊ณผ dp2๊ฐ ๊ฐ๊ฐ nums์ ๊ธธ์ด์ ๊ฐ์ผ๋ฏ๋ก O(n * 2)
> O(n * 2) ~= O(n)
"""
def solve_dp(self, nums: List[int]) -> int:
if len(nums) <= 3:
return max(nums)
dp1 = [0] * len(nums)
dp1[0], dp1[1] = nums[0], max(nums[0], nums[1])
max_dp1 = max(dp1[0], dp1[1])
for i in range(2, len(nums) - 1):
dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i])
max_dp1 = max(max_dp1, dp1[i])
dp2 = [0] * len(nums)
dp2[0], dp2[1] = 0, nums[1]
max_dp2 = max(dp2[0], dp2[1])
for i in range(2, len(nums)):
dp2[i] = max(dp2[i - 1], dp2[i - 2] + nums[i])
max_dp2 = max(max_dp2, dp2[i])
return max(max_dp1, max_dp2)
class _LeetCodeTestCases(TestCase):
def test_1(self):
nums = [2, 3, 2]
output = 3
self.assertEqual(Solution.rob(Solution(), nums), output)
def test_2(self):
nums = [1, 2, 3, 1]
output = 4
self.assertEqual(Solution.rob(Solution(), nums), output)
if __name__ == '__main__':
main()