File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxProfit (self , prices : List [int ]) -> int :
3
+ """
4
+ 가장 수익을 많이 얻을 수 있도록 저점에 매수, 고점에 매도
5
+ 매수와 매도는 서로 다른 날
6
+
7
+ min_price를 빼가면서 price 업데이트
8
+
9
+ Time Complexity : O(n)
10
+ Space Complexity : O(1)
11
+ """
12
+
13
+ min_price = max (prices )
14
+ days = len (prices )
15
+
16
+ for day in range (days ):
17
+ min_price = min (prices [day ], min_price )
18
+ prices [day ] -= min_price
19
+
20
+ return max (prices )
21
+
22
+
23
+
Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+ class Solution :
4
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
5
+ # Naive Solution : Sort string
6
+
7
+ # 각 단어마다 모두 정렬을 한 뒤 해당 값을 hash로 사용하여 딕셔너리에 추가하는 방법
8
+ # strs[i].length = k
9
+ # Time Complexity : O(n*klog(k))
10
+ # Space Complexity : O(n*k)
11
+
12
+ """
13
+
14
+ n = len(strs)
15
+ word_dict = defaultdict(list)
16
+
17
+ for word in strs:
18
+ key = hash(''.join(sorted(word)))
19
+ word_dict[key].append(word)
20
+
21
+ ret = []
22
+ for value in word_dict.values():
23
+ ret.append(value)
24
+ return ret
25
+ """
26
+
27
+ # Better Solution : Counting
28
+
29
+ # anagram 의 특성 중 알파벳 카운트 갯수가 같다는 것을 이용
30
+ # 카운트 갯수를 활용하여 key 값으로 처리
31
+ # Time Complexity : O(n*k)
32
+ # Space Complexity : O(n*k)
33
+ word_dict = defaultdict (list )
34
+
35
+ for word in strs :
36
+ freq = [0 ]* 26
37
+ for char in word :
38
+ freq [ord (char ) - ord ('a' )] += 1
39
+ word_dict [tuple (freq )].append (word )
40
+
41
+ return list (word_dict .values ())
42
+
43
+
44
+
You can’t perform that action at this time.
0 commit comments