Katkat

Maximize capacity with primary-backup pairing

AmazonSoftware Engineer · Online Assessment

Last updated

This problem tests your ability to optimize resource pairing using greedy strategies or sorting to maximize total capacity under specific pair-wise constraints.

Problem Statement

You are managing a server cluster where each server has a specific capacity. To ensure high availability, you must pair servers into Primary-Backup sets. A pair consists of two distinct servers. The 'capacity' of a pair is defined as the minimum capacity of the two servers in that pair.

Given an array of integers capacities representing the capacity of each server, your goal is to partition all servers into pairs such that the sum of the capacities of all pairs is maximized. Each server can be part of exactly one pair. You are guaranteed that the total number of servers is even.

Function Signature

def maximize_total_capacity(capacities: list[int]) -> int:
    pass

Constraints

  • 2 <= len(capacities) <= 10^5
  • len(capacities) is always even.
  • 1 <= capacities[i] <= 10^4

Examples

Example 1:

  • Input: capacities = [1, 4, 2, 3]
  • Output: 4
  • Explanation: Possible pairings: (1, 2) and (3, 4). Min(1, 2) = 1, Min(3, 4) = 3. Sum = 1 + 3 = 4.

Example 2:

  • Input: capacities = [6, 2, 6, 5, 1, 2]
  • Output: 9
  • Explanation: Pairing (1, 2), (2, 5), (6, 6) gives min values: 1 + 2 + 6 = 9.

Edge Cases

  • Arrays with duplicate capacity values.
  • Arrays where all capacities are the same.
  • Arrays with very large or very small capacity ranges.

Hints

Hint 1

Consider how the minimum value of a pair affects the total sum; you want to avoid 'wasting' large values by pairing them with very small ones.

Hint 2

Try sorting the capacities array in non-decreasing order first.

Hint 3

Observe that by sorting the array, pairing adjacent elements `(arr[i], arr[i+1])` ensures that the smaller element of each pair is as large as possible.

Follow-up questions

  • What is the time complexity of your solution, and can it be optimized further?
  • How would the logic change if you were required to form groups of three instead of pairs?
  • If you could remove one server before pairing to maximize the remaining sum, how would you decide which one to remove?