Skip to content

Commit 667ffe0

Browse files
author
sangbeenmoon
committed
LCS, house-robber.
1 parent 79a9055 commit 667ffe0

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

โ€Žhouse-robber/sangbeenmoon.pyโ€Ž

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,29 @@ def rob(self, nums: List[int]) -> int:
1414
dp[i] = max(dp[i-2] + nums[i] , dp[i-1])
1515

1616
return dp[len(nums) - 1]
17+
18+
19+
20+
21+
22+
# dp[i] = max(dp[i-1], dp[i-2] + num[i])
23+
# TC : O(n)
24+
# SC : O(n)
25+
26+
class Solution:
27+
def rob(self, nums: List[int]) -> int:
28+
dp = [0] * len(nums)
29+
30+
dp[0] = nums[0]
31+
32+
if len(nums) == 1:
33+
return dp[0]
34+
35+
dp[1] = max(nums[0],nums[1])
36+
37+
for i in range(2, len(nums)):
38+
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
39+
40+
return max(dp)
41+
42+

โ€Žlongest-consecutive-sequence/sangbeenmoon.pyโ€Ž

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,36 @@ def longestConsecutive(self, nums: List[int]) -> int:
1616
answer = max(answer , length)
1717

1818
return answer
19+
20+
21+
22+
# ์ •๋ ฌํ•˜๋ฉด ์‰ฌ์šด๋ฐ O(n)์ด ํ•„์š”ํ•˜๋„ค โ†’ set์œผ๋กœ ์กฐํšŒ๋ฅผ O(1)๋กœ โ†’ ๊ทผ๋ฐ ์ค‘๋ณต์œผ๋กœ ์„ธ๋„ค โ†’ ์‹œ์ž‘์ ์—์„œ๋งŒ ์„ธ์ž
23+
24+
# TC : O(n)
25+
# SC : O(n)
26+
27+
class Solution:
28+
def longestConsecutive(self, nums: List[int]) -> int:
29+
s = set()
30+
31+
for num in nums:
32+
s.add(num)
33+
34+
ans = 0
35+
36+
for num in s:
37+
if num - 1 in s:
38+
continue
39+
40+
sub_ans = 1
41+
next_num = num + 1
42+
while next_num in s:
43+
sub_ans = sub_ans + 1
44+
next_num = next_num + 1
45+
ans = max(ans, sub_ans)
46+
47+
return ans
48+
49+
50+
51+

0 commit comments

Comments
ย (0)