Here, we have to do three things optimally.
Choose the targeted city, where we want to invite the heroes.
Choose exactly one hero from each type.
Distribute the energy drinks among the invited heroes.
The number of cities can be at most . Thus, it is obvious to invite the heroes to each city and find the optimal result in for that city. The final complexity will be .
Let’s group the heroes by their types. So, there are groups and from each group, we have to invite exactly one hero. It can be done using dynamic programming (0-1 knapsack).
Suppose, we have invited the heroes of index and the targeted city is where . The power of invited heroes after gathering without drinking energy drinks are . .
Now, the cities of the first invited heroes are on the left side of the targeted city. We want to distribute the energy drinks optimally among these heroes. The leftmost hero of index can reach index without losing any power by drinking energy drinks. So there are heroes at index with power and respectively where ( is the power of the hero of city after reaching at city without drinking energy drink and starting from city ).
If both and are greater than , then we can take anyone between the heroes of index and at city giving all the energy drinks between city and . Both of the results are optimal.
If is , then we have to take the hero of city at city giving the energy drinks between city and .
If is , then we must take the hero of index at giving the energy drinks between city and . This is because taking will not contribute anything and the energy drinks between city and have no effects on the optimal result in this case.
So we get the optimal result by moving the hero of city or with initial power (drinking energy drinks while moving will not decrease his power and preserve the initial power). It is always better to assign energy drinks to exactly one hero to the left of and to exactly one hero to the right of .
Then our problem comes down to a modified 0-1 knapsack, where with taking the heroes, we also need to track if we have already assigned the drinks to a left hero or a right hero. Complexity .