Compute total revenue from greedy VM rentals
AmazonSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to use greedy strategies combined with efficient data structures to manage resource allocation and optimize revenue based on priority-based demand.
Problem Statement
You are managing a cloud provider's VM rental system. You have n different VM types, each with a fixed hourly price. You receive a sequence of m rental requests, where each request specifies a VM type and the duration of the rental.
However, there is a constraint: at any given time, you can only rent out a VM if you have the 'optimal' available unit. For this system, the 'optimal' unit is defined as the VM currently available that has the highest price. If multiple units of the same type are available, you always pick the one that has been idle for the longest duration (FIFO) among that type.
Given a list of n VM types with their respective hourly prices and a sequence of m requests (type_id, duration), compute the total revenue generated. If a request cannot be fulfilled because no VMs of that type are available, that request is ignored.
Function Signature
def compute_total_revenue(vm_prices: List[int], inventory: List[int], requests: List[Tuple[int, int]]) -> int:
vm_prices: A list where indexiis the price of VM typei.inventory: A list where indexiis the initial count of available VMs of typei.requests: A list of tuples(type_id, duration).
Examples
Example 1:
vm_prices = [10, 20, 30],inventory = [1, 1, 1],requests = [(0, 5), (2, 2), (1, 3)]- Request (0, 5): 1 unit of type 0 rented. Revenue: 1 * 10 * 5 = 50.
- Request (2, 2): 1 unit of type 2 rented. Revenue: 50 + (1 * 30 * 2) = 110.
- Request (1, 3): 1 unit of type 1 rented. Revenue: 110 + (1 * 20 * 3) = 170.
- Output: 170
Constraints
n(number of types) <= 10^4m(number of requests) <= 10^5duration<= 100- Prices are positive integers.
Hints
Hint 1
Consider using a data structure that allows you to quickly find the VM type with the highest price.
Hint 2
Since inventory levels change over time, maintain the count of available VMs for each type and update them after each request.
Hint 3
A Max-Heap or a sorted list can help identify the highest-priced VM type efficiently if the inventory is dynamically managed.
Follow-up questions
- How would your approach change if VMs were returned to the inventory after a certain time T has elapsed?
- What if you were required to optimize for the 'least expensive' VM instead of the most expensive one to minimize cost for the user?
- How does the time complexity change if you need to support an update operation that changes the price of a VM type in the middle of the request stream?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.