Maximum Server Health Sum
You are managing a data center and need to select servers to maximize the total health score of your facility.
You are given two integer arrays, health and serverType, where health[i] is the health score of the $i$-th server and serverType[i] is its type. You are also given an integer k representing the maximum number of distinct server types you can include in your facility.
If you choose a specific server type, you must include all servers of that type to maximize your health sum. Your goal is to select at most k distinct types such that the sum of the health scores of all selected servers is maximized.
Example 1
Input
health = [4, 5, 5, 6], serverType = [1, 2, 1, 2], k = 1Output
11Explanation
First, we calculate the total health for each distinct server type: - **Type 1**: Health is 4 + 5 = 9 - **Type 2**: Health is 5 + 6 = 11 Since $k = 1$, we can pick at most one type. Picking Type 2 gives us the maximum health sum of 11.
Example 2
Input
health = [10, 2, 3, 4, 5], serverType = [1, 1, 2, 3, 2], k = 2Output
20Explanation
Totals per type: Type 1 = 12, Type 2 = 8, Type 3 = 4. Picking the top 2 types (1 and 2) gives 12 + 8 = 20.
Example 3
Input
health = [-5, 10, 20], serverType = [1, 2, 2], k = 1Output
30Explanation
Even though $k=1$, we only pick Type 2 because picking Type 1 would decrease the total health due to its negative value.
Constraints
n == health.length == serverType.length1 <= n <= 10⁵1 <= k <= n-10⁴ <= health[i] <= 10⁴1 <= serverType[i] <= 10⁹
Maximum Server Health Sum
Overview
The objective is to select at most k distinct server types to maximize the total health score. A key constraint is that if we select a server type, we must include all servers associated with that type.
The problem can be broken down into three logical steps:
- Group and Sum: Aggregate the total health for each unique server type.
- Filter: Since we want to maximize the sum, we should ignore any server type whose total aggregated health is negative or zero, as adding them would not help (or would even hurt) our total.
- Selection: Sort the positive aggregated health scores in descending order and pick the top
k(or fewer, if fewer thankpositive types exist).
Brute Force
A brute force approach would involve generating every possible combination of server types up to size k, calculating the sum for each combination, and keeping track of the maximum. However, with up to $10^5$ servers and many distinct types, the number of combinations would be astronomically high.
A slightly more "informed" brute force would be to aggregate the sums using a dictionary and then use nested loops to find the best k types, but even this is inefficient compared to sorting.
Implementation
def max_server_health(health: list[int], serverType: list[int], k: int) -> int:
# Aggregate health by type
type_sums = {}
for h, t in zip(health, serverType):
type_sums[t] = type_sums.get(t, 0) + h
# Extract sums into a list
all_sums = list(type_sums.values())
# Brute force selection: sort and pick top k
# Sorting is actually the bottleneck here, but for brute force
# explanation, we treat the aggregation and simple selection logic.
all_sums.sort(reverse=True)
max_total = 0
count = 0
for s in all_sums:
if count < k and s > 0:
max_total += s
count += 1
else:
break
return max_total
Time complexity: O(N log N) — Dominated by sorting the distinct server type sums. Space complexity: O(N) — Storing the health sums for each unique server type in a hash map.
Optimal / Best Approach
The optimal approach refines the aggregation and selection process. We use a hash map (dictionary in Python) to calculate the total health for each serverType in a single pass. After calculating these totals, we only care about the values that are greater than zero. We sort these positive totals in descending order and sum the first min(k, len(positive_totals)) values.
Implementation
from collections import defaultdict
def max_server_health(health: list[int], serverType: list[int], k: int) -> int:
# Use a dictionary to aggregate health sums for each server type
type_to_health = defaultdict(int)
for i in range(len(health)):
type_to_health[serverType[i]] += health[i]
# Filter for types that have a positive total health contribution
# We only care about positive sums because k is a maximum limit,
# not a requirement to pick exactly k.
positive_sums = [total for total in type_to_health.values() if total > 0]
# Sort sums in descending order to pick the best contributors first
positive_sums.sort(reverse=True)
# Take the top k positive sums
return sum(positive_sums[:k])
Time complexity: O(N + M log M) — Where $N$ is the number of servers and $M$ is the number of distinct server types. We iterate through $N$ servers once to build the map, then sort $M$ totals. Space complexity: O(M) — We store the aggregated health sum for each of the $M$ distinct server types.
Why this works
- Aggregation: Since we must take all servers of a chosen type, the "unit" of our decision-making is the total health of that type.
- Greedy Selection: This problem exhibits optimal substructure. To get the maximum total health from
kchoices, we should always pick the types with the highest individual total health first. - Handling Negatives: If a server type has a total health of -5, including it will always result in a smaller sum than excluding it. Since the problem allows us to pick at most
ktypes, we are never forced to pick a negative contributor.
Comments on the solution
No comments on the solution yet. Start a thread about the editorial or your own approach.
No comments yet for Maximum Server Health Sum. Be the first to start the thread.
No submissions recorded for this problem yet. Use Submit in the editor — each judge run is stored here.
Output
Input
Expected
Your output
Run to see your output.