Heaviest Set of Non-Adjacent Nodes
You are given an undirected graph whose nodes carry positive weights. Choose a set of nodes such that no two chosen nodes are joined by an edge, and return the largest possible total weight.
Nodes are numbered 0 to n - 1; node i weighs weights[i], and edges[j] = [u, v] joins u and v. The graph may contain cycles and may be disconnected. The empty set is allowed.
weights = [5, 1, 2, 5], edges = [[0,1], [1,2], [2,3], [3,0]] -> 7 // nodes 0 and 2 weights = [4, 9, 4], edges = [[0,1], [1,2]] -> 9 // the middle node
1 <= n <= 20. The interviewer said only a graph; ask whether it is a path or a tree before reaching for the general method.
Hints
Hint 1
On a path this is House Robber, and on a tree it is a two-state DFS. A general graph has no such ordering, which is why n is small.
Hint 2
Take any remaining node v. Either it is not chosen, or it is chosen and none of its neighbours can be.
Hint 3
Represent the set of remaining nodes as a bitmask and each node's neighbours as a bitmask. Then best[mask] depends only on smaller masks.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.