diff --git a/binary-tree-maximum-path-sum/moonjonghoo.js b/binary-tree-maximum-path-sum/moonjonghoo.js new file mode 100644 index 000000000..fd42563bc --- /dev/null +++ b/binary-tree-maximum-path-sum/moonjonghoo.js @@ -0,0 +1,17 @@ +var maxPathSum = function (root) { + let maxSum = -Infinity; + + function dfs(node) { + if (node === null) return 0; // 6) Base Case + const left = Math.max(dfs(node.left), 0); // 8) Pruning + const right = Math.max(dfs(node.right), 0); // 8) Pruning + + const currentSum = left + node.val + right; // 9) Pivot Sum + maxSum = Math.max(maxSum, currentSum); // 7) Global Max + + return node.val + Math.max(left, right); // 10) Return Value + } + + dfs(root); // 4) DFS 시작 + console.log(maxSum); // 최종 답 출력 +}; diff --git a/merge-intervals/moonjonghoo.js b/merge-intervals/moonjonghoo.js new file mode 100644 index 000000000..589c6f171 --- /dev/null +++ b/merge-intervals/moonjonghoo.js @@ -0,0 +1,21 @@ +function merge(intervals) { + if (intervals.length === 0) return []; + + // 1) 시작점 기준 정렬 + intervals.sort((a, b) => a[0] - b[0]); + + const merged = []; + for (const interval of intervals) { + // 2) 결과 배열의 마지막 구간 + const last = merged[merged.length - 1]; + + // 3) 겹치지 않으면 새 구간 추가 + if (!last || interval[0] > last[1]) { + merged.push(interval); + } else { + // 4) 겹치면 병합: 끝점 확장 + last[1] = Math.max(last[1], interval[1]); + } + } + return merged; +} diff --git a/number-of-connected-components-in-an-undirected-graph/moonjonghoo.js b/number-of-connected-components-in-an-undirected-graph/moonjonghoo.js new file mode 100644 index 000000000..cbea5e8b1 --- /dev/null +++ b/number-of-connected-components-in-an-undirected-graph/moonjonghoo.js @@ -0,0 +1,30 @@ +// Time Complexity: O(n + e) — 노드 n개와 간선 e개를 한 번씩 순회 +// Space Complexity: O(n + e) — 인접 리스트 저장 O(n+e), 재귀 호출 스택 최악 O(n) +function countComponents(n, edges) { + // 인접 리스트 생성 + const adj = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + } + + const visited = Array(n).fill(false); + let count = 0; + + function dfs(u) { + visited[u] = true; + for (const v of adj[u]) { + if (!visited[v]) dfs(v); + } + } + + // 모든 노드 순회 + for (let i = 0; i < n; i++) { + if (!visited[i]) { + count++; + dfs(i); + } + } + + return count; +}