Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7fe13b4

Browse files
Create 3593-minimum-increments-to-equalize-leaf-paths.js
1 parent bab817d commit 7fe13b4

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number[]} cost
5+
* @return {number}
6+
*/
7+
var minIncrease = function (n, edges, cost) {
8+
const tree = Array.from({ length: n }, () => [])
9+
10+
for (const e of edges) {
11+
tree[e[0]].push(e[1])
12+
tree[e[1]].push(e[0])
13+
}
14+
15+
const changes = [0]
16+
dfs(0, -1, tree, cost, changes)
17+
18+
return changes[0]
19+
}
20+
21+
function dfs(node, parent, tree, cost, changes) {
22+
const childCosts = []
23+
24+
for (const nei of tree[node]) {
25+
if (nei === parent) {
26+
continue
27+
}
28+
29+
const subCost = dfs(nei, node, tree, cost, changes)
30+
childCosts.push(subCost)
31+
}
32+
33+
if (childCosts.length === 0) {
34+
return cost[node]
35+
}
36+
37+
const maxCost = Math.max(...childCosts)
38+
39+
for (const c of childCosts) {
40+
if (c < maxCost) {
41+
changes[0]++
42+
}
43+
}
44+
45+
return cost[node] + maxCost
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /