← Questions

Maximum stability of a server group

0
AmazonCoding

A coding interview question asked at Amazon. It tests greedy, sorting and prefix sum.

A cloud provider offers n servers. Server i has two positive integer scores: reliability[i] and availability[i].

A client deploys on any non-empty group of servers. A group is only as available as its weakest member, and its reliabilities add up. So the stability of a group is:

stability = min(availability of servers in the group) * sum(reliability of servers in the group)

Implement get_max_stability(reliability, availability) that returns the largest stability any group can reach. The value can be very large, so return it modulo 10^9 + 7. Pick the group by its true stability, not by the reduced value.

Constraints

  • 1 <= n <= 10^5
  • len(reliability) == len(availability) == n
  • 1 <= reliability[i], availability[i] <= 10^6

Example 1

reliability  = [2, 3, 1]
availability = [5, 1, 4]
output: 12

Choose servers 0 and 2. The minimum availability is 4 and the reliabilities sum to 3, so the stability is 12. Server 0 alone scores 10, and all three servers score only 6.

Example 2

reliability  = [10, 1]
availability = [1, 100]
output: 100

Server 1 alone scores 100 * 1 = 100. Adding server 0 drops the minimum availability to 1, for a score of 11.

Clarifying questions

  • Does "modulo 10^9 + 7" apply only to the returned value? (Yes: compare the true values.)
  • Can the true value overflow 64 bits? (At most about 10^17, so no.)
  • Must the group be contiguous in the input? (No.)
  • Should we return the group?

What a strong answer covers

  • Fixes the server with the lowest availability in the group. The best group then takes every server with availability at least that, since more reliability always helps.
  • Sorts servers by availability, highest first, keeps a running sum of reliability, and scores availability x running sum at each server. That is O(n log n).
  • Handles equal availabilities by adding all of them before scoring, or by noticing that scoring each one is still correct.
  • Applies the modulo only at the end.
  • Tests both examples, n = 1, all equal availabilities, and a case where one server alone wins.

Follow-ups

  • The group has at most k servers: keep a min-heap of the best reliabilities.
  • The group must be a contiguous block of the input: a monotonic stack.
  • Return the group.
  • Servers arrive one at a time, with the best stability asked after each.

Where it's asked

What it tests

greedy · sorting · prefix sum

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