-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
60 lines (56 loc) · 1.33 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
private List<Integer>[] g;
private int[] nums;
private int t;
public int componentValue(int[] nums, int[][] edges) {
int n = nums.length;
g = new List[n];
this.nums = nums;
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
int s = sum(nums), mx = max(nums);
for (int k = Math.min(n, s / mx); k > 1; --k) {
if (s % k == 0) {
t = s / k;
if (dfs(0, -1) == 0) {
return k - 1;
}
}
}
return 0;
}
private int dfs(int i, int fa) {
int x = nums[i];
for (int j : g[i]) {
if (j != fa) {
int y = dfs(j, i);
if (y == -1) {
return -1;
}
x += y;
}
}
if (x > t) {
return -1;
}
return x < t ? x : 0;
}
private int sum(int[] arr) {
int x = 0;
for (int v : arr) {
x += v;
}
return x;
}
private int max(int[] arr) {
int x = arr[0];
for (int v : arr) {
x = Math.max(x, v);
}
return x;
}
}