← Questions

Pair servers as primary and backup to maximize memory

0
AmazonCodingLast asked Jan 2026

A coding interview question asked in Amazon's online assessment, last asked Jan 2026. It tests greedy and sorting.

Each server has a memory size. Choose servers and group them into disjoint pairs; in each pair one server is the primary and the other its backup. A backup must have at least as much memory as its primary. The system's capacity is the total memory of all primaries. Return the largest capacity you can reach. Servers left out of every pair contribute nothing.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_capacity(memory: list[int]) -> int

Example

max_capacity([2, 4, 3, 1, 2])      ->  5    # pairs (3 primary, 4 backup) and (2, 2); the 1 is left out
max_capacity([1, 2, 3, 4, 5, 6])   ->  9    # (5, 6), (3, 4), (1, 2): primaries 5 + 3 + 1
max_capacity([7])                  ->  0    # one server cannot form a pair

Constraints

  • 0 <= len(memory) <= 10^5; 1 <= memory[i] <= 10^9.
  • The answer can exceed 32 bits.

Clarifying questions

  • Must every server be used, or may some be left out?
  • Can two servers with equal memory back each other up?
  • Can one backup serve several primaries? (No: pairs are disjoint.)

What a strong answer covers

  • In any pair the primary is the smaller server, so the task is to pick pairs maximising the sum of each pair's minimum.
  • Sort descending and pair neighbours (m[0], m[1]), (m[2], m[3]), …; the answer is m[1] + m[3] + …. An exchange argument shows pairing adjacent sorted values is optimal, and with an odd count the smallest server is the one left out.
  • O(n log n) time, or O(n + range) with counting sort.
  • Tests: empty, a single server, all equal, odd and even counts.

Follow-ups

  • The number of pairs is fixed at k. What changes?
  • A backup must have at least twice its primary's memory. Does the greedy still work?

Where it's asked

  • Amazon · Online assessment · Last asked Jan 2026Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

greedy · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding