File tree Expand file tree Collapse file tree 3 files changed +55
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 시간복잡도 O(n)
2
+ # 공간복잡도 O(1)
3
+ class Solution :
4
+ def maxProfit (self , prices : list [int ]) -> int :
5
+ min_p = prices [0 ] # 최소 가격 설정 : 배열의 첫 번째 가격
6
+ cur = 0
7
+ max_p = 0
8
+ for n in prices :
9
+ if n < min_p : # 현재 가격이 최소 가격보다 작다면 최소가격 갱신
10
+ min_p = n
11
+ cur = n - min_p # 현재 이익 계산
12
+ if max_p < cur : # 현재 이익과 최대로 얻을 수 있는 이익 비교
13
+ max_p = cur # 최대 이익 갱신신
14
+
15
+ return max_p
16
+
17
+
18
+
19
+
Original file line number Diff line number Diff line change
1
+ #시간복잡도 O(n * klogk)
2
+ #공간복잡도 O(n * k)
3
+ # => n개의 단어 * 각 단어의 k만큼의 길이
4
+ class Solution :
5
+ def groupAnagrams (self , strs : list [str ]) -> list [list [str ]]:
6
+ ans = {}
7
+
8
+ for word in strs :
9
+ # 단어의 문자를 정렬 후 키로 사용
10
+ sortedWord = '' .join (sorted (word )) # sorted()의 시간복잡도 : O(klogk)
11
+ # 초기 리스트 생성
12
+ if sortedWord not in ans :
13
+ ans [sortedWord ] = []
14
+ ans [sortedWord ].append (word )
15
+
16
+ # 딕셔너리의 value를 list로 변환
17
+ ansLst = list (ans .values ())
18
+ return ansLst
19
+
Original file line number Diff line number Diff line change
1
+ #시간복잡도 O(N * M)
2
+ #공간복잡도 O(N)
3
+ class Solution :
4
+ def wordBreak (self , s : str , wordDict : list [str ]) -> bool :
5
+ # 문자열 s의 0번째부터 i번째까지의 문자열이 wordDict의 단어로 분할될 수 있으면 True
6
+ # 빈 문자열 s[0:0]은 항상 분할이 가능하므로 dp[0] = True
7
+ dp = [False ] * (len (s ) + 1 )
8
+ dp [0 ] = True
9
+ for i in range (1 , len (s ) + 1 ):
10
+ for word in wordDict :
11
+ # 현재 word가 i - len(word)부터 i번째까지의 s의 부분문자열과 일치한다면 True
12
+ # 바로 이전의 지점이 True이고 word만큼의 s 부분문자열이 wordDict 내에 존재한다면 dp[i] = True
13
+ if i >= len (word ) and dp [i - len (word )] and s [i - len (word ):i ] == word :
14
+ dp [i ] = True
15
+ break
16
+ return dp [- 1 ]
17
+
You can’t perform that action at this time.
0 commit comments