Queen's Kingdom

You are given a tree representing a kingdom with n cities connected by n - 1 two-way roads, represented by a 2D array edges. The cities are numbered from 1 to n, and city 1 is the capital.

You must select exactly k cities to develop industry, while the remaining cities will develop tourism. The capital can be chosen as either type.

Every year, each Industry City sends an envoy to the capital along the shortest path. An envoy's happiness is equal to the number of Tourism Cities they pass through (including the destination if the capital is a Tourism City).

Return the maximum possible sum of happiness of all envoys if you choose the k Industry Cities optimally.

Example 1:

Input: k = 4, edges = [[1, 2], [1, 3], [1, 4], [3, 5], [3, 6], [4, 7]]

Output: 7

Explanation:

Choose cities 2, 5, 6, and 7 as Industry Cities.

  • The envoy from 2 passes through 1 (1 Tourism City) -> Happiness = 1.
  • The envoys from 5, 6, and 7 pass through 3 or 4 and then 1 (2 Tourism Cities) -> Happiness = 2 each.
  • Total happiness = 1 + 2 + 2 + 2 = 7.

Example 2:

Input: k = 1, edges = [[1, 2], [1, 3], [2, 4]]

Output: 2

Explanation:

Choose city 4 as the Industry City. The path to 1 is 4 -> 2 -> 1. Both 2 and 1 are Tourism Cities. Happiness = 2.

Now Your Turn!

Pick the correct output for the given input

Input: k = 5, edges = [[7, 5], [1, 7], [6, 1], [3, 7], [8, 3], [2, 1], [4, 5]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= edges.length
  • 1 <= edges.length <= 2*105
  • edges[i].length == 2
  • 1 <= u, v <= edges.length + 1
  • The given edges form a valid tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long maxHappiness(int k, vector<vector<int>>& edges) {
// Write your code here
}
};
Test Case

Input:

Edges
K