Skip to main content

Maximum Server Health Sum

easy
Software engineer

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 = 1

Output

11

Explanation

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 = 2

Output

20

Explanation

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 = 1

Output

30

Explanation

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.length
  • 1 <= n <= 10⁵
  • 1 <= k <= n
  • -10⁴ <= health[i] <= 10⁴
  • 1 <= serverType[i] <= 10⁹

OA

ArrayGreedyHash TableSorting
Language
Code editor loads in the browser.

Output

Input

[4,5,5,6]
[1,2,1,2]
1

Expected

11

Your output

Run to see your output.