Compute total revenue from greedy VM rentals
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
You manage **n** VM types. VM type *i* starts with inventory `a[i]` (number of available instances).
There are **m** customers arriving one by one. For each customer:
1. The customer rents **one** instance from the VM type that currently has the **largest** inventory (if there are ties, any tied type may be chosen).
2. Let `maxInv` be that largest inventory *before* the rental.
3. Let `minPosInv` be the **smallest positive** inventory among all VM types *before* the rental (ignore VM types with inventory 0).
4. The revenue from this rental is `maxInv + minPosInv`.
5. After the rental, the chosen VM type’s inventory decreases by 1.
Assume it is guaranteed that the total initial inventory is at least `m`.
**Task:** Compute the total revenue after processing all `m` customers.
#### Input
- Integers `n`, `m`
- Array `a[1..n]` of non-negative integers
#### Output
- A single integer: the total revenue.
#### Notes
- If multiple VM types share the same maximum inventory, any choice among them leads to a valid simulation.
- `minPosInv` is always defined because total remaining inventory is positive while customers remain.
#### Example
If `a = [2, 1]`, `m = 2`:
- Step 1: `maxInv=2`, `minPosInv=1`, revenue `3`, inventories -> `[1,1]`
- Step 2: `maxInv=1`, `minPosInv=1`, revenue `2`, inventories -> `[0,1]`
Total revenue = `5`.
Quick Answer: This question evaluates understanding of greedy allocation strategies and the ability to maintain dynamic summaries (tracking current maximum and smallest positive inventories) under sequential state updates, reflecting algorithmic thinking and data-structure manipulation.
Part 1: Compute Total Revenue from Greedy VM Rentals
You are given the current stock of n VM types and an integer m. Customers arrive one by one. For each customer, choose a VM type with the largest positive stock. Let max_stock be that chosen stock before the rental, and let min_stock be the smallest positive stock among all VM types before the rental. The revenue from this rental is max_stock + min_stock. Then decrease the chosen stock by 1. If all stocks are 0 before some request, stop early and ignore the remaining customers. Return the total revenue after processing at most m requests.
Constraints
- 1 <= len(stocks) <= 2 * 10^5
- 0 <= stocks[i] <= 10^9
- 0 <= m <= 2 * 10^5
- The answer may exceed 32-bit integer range.
Examples
Input: ([4, 2, 1], 4)
Expected Output:
Explanation: The revenues are 5, 4, 3, and 3, for a total of 15.