Maximize total cluster throughput from median-of-three servers
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests greedy, sorting and arrays.
You manage a fleet of host servers. hostThroughput[i] is the throughput of server i (a non-negative integer).
Group servers into clusters of exactly three distinct servers. Build as many clusters as possible, which is n // 3. A server can be in at most one cluster, and servers left over are not used.
A cluster's throughput is the median of its three servers' throughputs (the middle value after sorting the three). Return the largest possible sum of cluster throughputs.
def max_throughput(host_throughput: list[int]) -> int: ...
Constraints
0 <= n <= 2 * 10^50 <= hostThroughput[i] <= 10^9- The answer can exceed 32 bits.
Example 1
Input: [4, 6, 3, 5, 4, 5]
Output: 9
Two clusters: {6, 5, 4} has median 5 and {5, 4, 3} has median 4, so the total is 9. No grouping does better.
Example 2
Input: [8, 1, 8, 2, 7, 3]
Output: 11
Grouping the three largest together, {8, 8, 7} and {3, 2, 1}, gives only 8 + 2 = 10. The grouping {8, 8, 1} and {7, 3, 2} gives 8 + 3 = 11, which is the best.
If n < 3, return 0.
Clarifying questions
- Is the number of clusters fixed at
n // 3, or could fewer clusters ever be better? (With non-negative values, more never hurts.) - Do the leftover servers have to be the smallest?
- Can servers have equal throughput?
- Should we return the clusters too?
What a strong answer covers
- Sorts the throughputs in descending order. Each cluster takes the next two largest servers and one of the smallest.
- So the medians are the 2nd, 4th, 6th, ... largest values,
n // 3of them. - Gives a swap argument for why pairing big servers with the smallest ones is optimal.
- That is O(n log n) time. Uses 64-bit sums.
- Tests both examples,
n < 3,nnot a multiple of 3, and all equal values.
Follow-ups
- Clusters of size
m, scored by the second-largest server. - Clusters must be contiguous in the input order.
- Maximize the smallest cluster throughput instead of the sum.
- Return the clusters.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
