Social feed~40 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedfs · traversal
A feed team studies how one post spreads. A post can pass from user a to user b when follows lists [a, b]. Users form loops: a post can go round a loop of users any number of times.
User v earns values[v] views the first time the post reaches them, and nothing after that. A post may start at any user and follow the links as far as it likes. Which total of views can it reach at most?
Write richest_chain(values, follows).
values.length users, numbered from 0.follows[i] is [a, b]: a post can pass from user a to user b. The same pair may appear more than once, and a differs from b.values[v] once.Input: values = [5, 3, 4, 2, 8, 1, 9], follows = [[0,1],[1,0],[1,2],[2,3],[3,2],[0,4],[4,5],[3,5],[6,0]]
Output: 26Users 0 and 1 pass the post to each other, and so do users 2 and 3. Together they form two loops of two users. A post that starts at user 6 can reach the loop of users 0 and 1, then user 4, then user 5: 9 + 8 + 8 + 1 = 26.
The solution first merges each loop into one node. The two passes below number the loops from the start of the post's flow, so every link between loops goes to a higher number.
| Loop | Users | Total | Loops after it | Best chain from it |
|---|---|---|---|---|
| 0 | 6 | 9 | 1 | 26 |
| 1 | 0, 1 | 8 | 2 and 3 | 17 |
| 2 | 4 | 8 | 4 | 9 |
| 3 | 2, 3 | 6 | 4 | 7 |
| 4 | 5 | 1 | none | 1 |
The table is filled from the last loop up. For loop 1, the best loop after it is loop 2 with 9, so its best chain is 8 + 9 = 17. For loop 0 it is 9 + 17 = 26.
Input: values = [2, 3, 4], follows = [[0,1],[1,2]]
Output: 9There is no loop. The post starts at user 0 and reaches all three users.
Input: values = [10, 20], follows = [[0,1],[1,0]]
Output: 30The two users pass the post to each other. Both count once.
1 ≤ values.length ≤ 100,000, and 0 ≤ values[v] ≤ 10^90 ≤ follows.length ≤ 100,000, and each link is [a, b] with 0 ≤ a, b < values.length and a ≠ bTrying every set of users a post could reach gives n × 2^n states, which is far beyond reach for 100,000 users. Even a search from each user costs n × (n + m), about 2 × 10^10 steps. Merging loops and filling one table costs about 10^6 steps. The total can reach 10^14, so it needs a 64-bit integer.