File tree Expand file tree Collapse file tree
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ prices를 순회하며 현재 최저값과의 차이를 구해서 최대 profit을 갱신한 뒤 최저값(구매가)를 갱신, 최종값을 리턴한다
3+
4+ 시간복잡도 O(N) - N은 prices의 length
5+ */
6+
7+ function maxProfit ( prices : number [ ] ) : number {
8+ let buy
9+ let result = 0
10+
11+ for ( let price of prices ) {
12+ if ( buy === undefined ) {
13+ buy = price
14+ continue
15+ }
16+ result = Math . max ( result , price - buy )
17+ buy = Math . min ( price , buy )
18+ }
19+
20+ return result
21+ }
Original file line number Diff line number Diff line change 1+ /*
2+ strs의 문자열들을 등장빈도를 바탕으로 계산한 특수 문자열로 전환하고 같은 것끼리 묶는다.
3+
4+ 시간복잡도 : O(N * K) - N은 strs의 개수, K는 strs의 길이. N 순회 안에 K 순회
5+ */
6+
7+ function groupAnagrams ( strs : string [ ] ) : string [ ] [ ] {
8+ const anagramMap = { }
9+ const result = strs . reduce ( ( acc , cur ) => {
10+ const charArray = new Array ( 26 ) . fill ( 0 )
11+
12+ for ( let char of cur ) {
13+ const charIdx = char . charCodeAt ( 0 ) - 'a' . charCodeAt ( 0 )
14+ charArray [ charIdx ] += 1
15+ }
16+
17+ const sortedValue = charArray . join ( '#' )
18+
19+ const targetIdx = anagramMap [ sortedValue ]
20+ if ( targetIdx !== undefined ) {
21+ acc [ targetIdx ] . push ( cur )
22+ } else {
23+ anagramMap [ sortedValue ] = acc . length
24+ acc . push ( [ cur ] )
25+ }
26+ return acc
27+ } , [ ] )
28+
29+ return result
30+ }
You can’t perform that action at this time.
0 commit comments