Skip to content

Commit 4c4eb21

Browse files
committed
feat: week5 문제풀이(221, 236, 238)
1 parent d52bb73 commit 4c4eb21

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# O(N) times, O(1) spaces
2+
# price[i] 가격으로 팔아서 가장 수익을 많이 내려면, i-1번째까지 중 가장 값이 싼 날짜에서 주식을 사면 된다
3+
class Solution:
4+
def maxProfit(self, prices: List[int]) -> int:
5+
max_profit = 0
6+
min_price = prices[0]
7+
8+
for price in prices:
9+
profit = price - min_price
10+
max_profit = max(max_profit, profit)
11+
min_price = min(min_price, price)
12+
13+
return max_profit
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# O(N) times, O(1) spaces
2+
class Solution:
3+
"""
4+
@param: strs: a list of strings
5+
@return: encodes a list of strings to a single string.
6+
"""
7+
def encode(self, strs):
8+
encoded_str = ""
9+
for str in strs:
10+
encoded_str += f"{len(str)}:{str}"
11+
return encoded_str
12+
13+
"""
14+
@param: str: A string
15+
@return: decodes a single string to a list of strings
16+
"""
17+
def decode(self, str):
18+
list_strs, start = [], 0
19+
while start < len(str):
20+
offset = str.find(":", start)
21+
s_length = int(str[start:offset])
22+
list_strs.append(str[offset+1:offset+1+s_length])
23+
start = offset+1+s_length
24+
return list_strs

group-anagrams/jinah92.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# O(N * NlogN) times, O(N) spaces
2+
class Solution:
3+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
4+
anagrams_dict = {}
5+
result = []
6+
7+
for str in strs: # N 시간 소요
8+
str_count = {}
9+
for s in str:
10+
if not s in str_count:
11+
str_count[s] = 1
12+
else:
13+
str_count[s] += 1
14+
anagrams_keys = []
15+
for key, val in sorted(str_count.items()): # 최대 N개의 dict items를 배열하므로 NlogN 시간 소요
16+
anagrams_keys.append(tuple([key, val]))
17+
18+
anagrams_key = tuple(anagrams_keys)
19+
if tuple(anagrams_keys) not in anagrams_dict:
20+
anagrams_dict[tuple(anagrams_keys)] = []
21+
anagrams_dict[tuple(anagrams_keys)].append(str)
22+
23+
24+
return list(anagrams_dict.values())

0 commit comments

Comments
 (0)