File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ // Step 1. 브루트 포스
2+ // 시간 복잡도: O(n²)
3+ const maxProfitBrute = ( prices ) => {
4+ let maxProfit = 0 ;
5+
6+ for ( let i = 0 ; i < prices . length ; i ++ ) {
7+ for ( let j = i + 1 ; j < prices . length ; j ++ ) {
8+ const profit = prices [ j ] - prices [ i ] ;
9+ maxProfit = Math . max ( maxProfit , profit ) ;
10+ }
11+ }
12+
13+ return maxProfit ;
14+ }
15+
16+ // Step 2. 최적 풀이
17+ // 시간 복잡도: O(n)
18+ const maxProfit = ( prices ) => {
19+ let minPrice = Infinity ;
20+ let maxProfit = 0 ;
21+
22+ for ( const price of prices ) {
23+ if ( price < minPrice ) {
24+ minPrice = price ;
25+ } else {
26+ maxProfit = Math . max ( maxProfit , price - minPrice ) ;
27+ }
28+ }
29+
30+ return maxProfit ;
31+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * TC: O(n * k log k) — 각 단어(k) 정렬 × n개
3+ * SC: O(n * k)
4+ */
5+ const groupAnagrams = ( strs ) => {
6+ const map = new Map ( ) ;
7+
8+ for ( const str of strs ) {
9+ const key = str . split ( "" ) . sort ( ) . join ( "" ) ;
10+
11+ if ( ! map . has ( key ) ) {
12+ map . set ( key , [ ] ) ;
13+ }
14+
15+ map . get ( key ) . push ( str ) ;
16+ }
17+
18+ return Array . from ( map . values ( ) ) ;
19+ } ;
You can’t perform that action at this time.
0 commit comments