Skip to content

2925. Maximum Score After Applying Operations on a Tree 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  long long maximumScoreAfterOperations(vector<vector<int>>& edges,
                                        vector<int>& values) {
    vector<vector<int>> tree(values.size());

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      tree[u].push_back(v);
      tree[v].push_back(u);
    }

    return accumulate(values.begin(), values.end(), 0L) -
           dfs(tree, 0, /*prev=*/-1, values);
  }

 private:
  // Returns the minimum of sum to be reduced.
  long dfs(const vector<vector<int>>& tree, int u, int prev,
           const vector<int>& values) {
    if (u > 0 && tree[u].size() == 1)
      return values[u];
    long childrenSum = 0;
    for (const int v : tree[u])
      if (v != prev)
        childrenSum += dfs(tree, v, u, values);
    return min(childrenSum, static_cast<long>(values[u]));
  }
};
 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
class Solution {
  public long maximumScoreAfterOperations(int[][] edges, int[] values) {
    List<Integer>[] tree = new ArrayList[values.length];

    for (int i = 0; i < values.length; ++i)
      tree[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      tree[u].add(v);
      tree[v].add(u);
    }

    return Arrays.stream(values).sum() - dfs(tree, 0, /*prev=*/-1, values);
  }

  private long dfs(List<Integer>[] tree, int u, int prev, int[] values) {
    if (u > 0 && tree[u].size() == 1)
      return values[u];
    long childrenSum = 0;
    for (final int v : tree[u])
      if (v != prev)
        childrenSum += dfs(tree, v, u, values);
    return Math.min(childrenSum, 1L * values[u]);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def maximumScoreAfterOperations(
      self,
      edges: list[list[int]],
      values: list[int],
  ) -> int:
    tree = [[] for _ in values]

    for u, v in edges:
      tree[u].append(v)
      tree[v].append(u)

    def dfs(u: int, prev: int) -> None:
      if u > 0 and len(tree[u]) == 1:
        return values[u]
      childrenSum = sum(dfs(v, u)
                        for v in tree[u]
                        if v != prev)
      return min(childrenSum, values[u])

    return sum(values) - dfs(0, -1)