File tree Expand file tree Collapse file tree 3 files changed +61
-0
lines changed
best-time-to-buy-and-sell-stock
encode-and-decode-strings Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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 ())
You can’t perform that action at this time.
0 commit comments