algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
1 shown · 0/261 solved

Maximum Subtree Adjustment Total

SilverCommunity Beta
Asked atmedia.net
Solve problem →
2000ms256MBAdded Aug 29, 2026

You are given a rooted tree with n nodes labelled 1 to n, described as n - 1 directed edges edges[i] = [parent, child]; exactly one node has no parent and is the root. Every node starts with a value of 0.

You must also perform tasks.length tasks, given by tasks, where each task tasks[i] = [delta, c1, c2, ..., ck] (k >= 1) requires you to choose exactly one of the listed candidate nodes and add delta (which may be negative) to that node and to every node in its subtree.

Choose the candidates so that the sum of all node values after every task is as large as possible. Return that sum.

Examples

Example 1

Input: n = 3, edges = [[1,2],[1,3]], tasks = [[10,2,3]]
Output: 10
Explanation: Nodes 2 and 3 are leaves; either choice adds 10 to a single node.

Example 2

Input: n = 4, edges = [[1,2],[2,3],[2,4]], tasks = [[5,1,2],[-3,2,3]]
Output: 17
Explanation: Task 1: choosing node 1 adds 5 to all four nodes (20), which beats node 2's three nodes. Task 2: choosing the leaf 3 subtracts 3 from one node (-3), which beats node 2's three nodes (-9). Total 20 - 3 = 17.
Read full statement →

Constraints

  • 1≤n≤1051 \leq n \leq 10^51≤n≤105
  • edges.length == n - 1; the edges form a single rooted tree
  • 1≤1 \leq1≤ tasks.length ≤105\leq 10^5≤105; the total number of candidates over all tasks is at most 2⋅1052 \cdot 10^52⋅105
  • −104≤-10^4 \leq−104≤ delta ≤104\leq 10^4≤104; every candidate is a valid node label

Details

Solved by6 people
Time limit2000ms
Memory256MB
AddedAug 29, 20262 weeks ago