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 cfe6316

Browse files
2973. Find Number of Coins to Place in Tree Nodes
1 parent 1e0e4bb commit cfe6316

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2973. Find Number of Coins to Place in Tree Nodes
5+
6+
var ans = [Int]()
7+
8+
func dfs(_ t: [[Int]], _ cost: [Int], _ root: Int, _ par: Int) -> [Int] {
9+
var usefulCost = [cost[root]]
10+
for n in t[root] {
11+
if n == par {
12+
continue
13+
}
14+
let v = dfs(t, cost, n, root)
15+
usefulCost.append(contentsOf: v)
16+
}
17+
18+
usefulCost.sort(by: >)
19+
let sz = usefulCost.count
20+
21+
if usefulCost.count < 3 {
22+
ans[root] = 1
23+
return usefulCost
24+
}
25+
26+
if usefulCost[1] * usefulCost[2] > usefulCost[sz - 1] * usefulCost[sz - 2] {
27+
ans[root] = usefulCost[0] * usefulCost[1] * usefulCost[2]
28+
} else {
29+
ans[root] = usefulCost[0] * usefulCost[sz - 1] * usefulCost[sz - 2]
30+
}
31+
32+
if ans[root] < 0 {
33+
ans[root] = 0
34+
}
35+
36+
if usefulCost.count <= 5 {
37+
return usefulCost
38+
}
39+
40+
return [
41+
usefulCost[0], usefulCost[1], usefulCost[2], usefulCost[sz - 2], usefulCost[sz - 1],
42+
]
43+
}
44+
45+
func placedCoins(_ edges: [[Int]], _ cost: [Int]) -> [Int] {
46+
ans = Array(repeating: 0, count: cost.count)
47+
var t = [[Int]](repeating: [], count: cost.count)
48+
for e in edges {
49+
t[e[0]].append(e[1])
50+
t[e[1]].append(e[0])
51+
}
52+
_ = dfs(t, cost, 0, -1)
53+
return ans
54+
}
55+
}

0 commit comments

Comments
(0)

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