File tree Expand file tree Collapse file tree 3 files changed +68
-0
lines changed
binary-tree-maximum-path-sum
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 3 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ var maxPathSum = function ( root ) {
2+ let maxSum = - Infinity ;
3+
4+ function dfs ( node ) {
5+ if ( node === null ) return 0 ; // 6) Base Case
6+ const left = Math . max ( dfs ( node . left ) , 0 ) ; // 8) Pruning
7+ const right = Math . max ( dfs ( node . right ) , 0 ) ; // 8) Pruning
8+
9+ const currentSum = left + node . val + right ; // 9) Pivot Sum
10+ maxSum = Math . max ( maxSum , currentSum ) ; // 7) Global Max
11+
12+ return node . val + Math . max ( left , right ) ; // 10) Return Value
13+ }
14+
15+ dfs ( root ) ; // 4) DFS ์์
16+ console . log ( maxSum ) ; // ์ต์ข
๋ต ์ถ๋ ฅ
17+ } ;
Original file line number Diff line number Diff line change 1+ function merge ( intervals ) {
2+ if ( intervals . length === 0 ) return [ ] ;
3+
4+ // 1) ์์์ ๊ธฐ์ค ์ ๋ ฌ
5+ intervals . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
6+
7+ const merged = [ ] ;
8+ for ( const interval of intervals ) {
9+ // 2) ๊ฒฐ๊ณผ ๋ฐฐ์ด์ ๋ง์ง๋ง ๊ตฌ๊ฐ
10+ const last = merged [ merged . length - 1 ] ;
11+
12+ // 3) ๊ฒน์น์ง ์์ผ๋ฉด ์ ๊ตฌ๊ฐ ์ถ๊ฐ
13+ if ( ! last || interval [ 0 ] > last [ 1 ] ) {
14+ merged . push ( interval ) ;
15+ } else {
16+ // 4) ๊ฒน์น๋ฉด ๋ณํฉ: ๋์ ํ์ฅ
17+ last [ 1 ] = Math . max ( last [ 1 ] , interval [ 1 ] ) ;
18+ }
19+ }
20+ return merged ;
21+ }
Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n + e) โ ๋
ธ๋ n๊ฐ์ ๊ฐ์ e๊ฐ๋ฅผ ํ ๋ฒ์ฉ ์ํ
2+ // Space Complexity: O(n + e) โ ์ธ์ ๋ฆฌ์คํธ ์ ์ฅ O(n+e), ์ฌ๊ท ํธ์ถ ์คํ ์ต์
O(n)
3+ function countComponents ( n , edges ) {
4+ // ์ธ์ ๋ฆฌ์คํธ ์์ฑ
5+ const adj = Array . from ( { length : n } , ( ) => [ ] ) ;
6+ for ( const [ u , v ] of edges ) {
7+ adj [ u ] . push ( v ) ;
8+ adj [ v ] . push ( u ) ;
9+ }
10+
11+ const visited = Array ( n ) . fill ( false ) ;
12+ let count = 0 ;
13+
14+ function dfs ( u ) {
15+ visited [ u ] = true ;
16+ for ( const v of adj [ u ] ) {
17+ if ( ! visited [ v ] ) dfs ( v ) ;
18+ }
19+ }
20+
21+ // ๋ชจ๋ ๋
ธ๋ ์ํ
22+ for ( let i = 0 ; i < n ; i ++ ) {
23+ if ( ! visited [ i ] ) {
24+ count ++ ;
25+ dfs ( i ) ;
26+ }
27+ }
28+
29+ return count ;
30+ }
You canโt perform that action at this time.
0 commit comments