Taro Logo

Maximum Profit of Operating a Centennial Wheel

Medium
Asked by:
Peak6
1 view
Topics:
Arrays

You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.

You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.

You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.

Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.

Example 1:

Input: customers = [8,3], boardingCost = 5, runningCost = 6
Output: 3
Explanation: The numbers written on the gondolas are the number of people currently there.
1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.
2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.
3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.
The highest profit was $37 after rotating the wheel 3 times.

Example 2:

Input: customers = [10,9,6], boardingCost = 6, runningCost = 4
Output: 7
Explanation:
1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.
2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.
3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.
4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.
5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.
6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.
7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.
The highest profit was $122 after rotating the wheel 7 times.

Example 3:

Input: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92
Output: -1
Explanation:
1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.
2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.
3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.
4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.
5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.
The profit was never positive, so return -1.

Constraints:

  • n == customers.length
  • 1 <= n <= 105
  • 0 <= customers[i] <= 50
  • 1 <= boardingCost, runningCost <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if it's impossible to achieve a non-negative profit across all possible rotations, and can the profit ever be strictly zero?
  2. If multiple rotation counts yield the exact same maximum profit, are we expected to return the minimum number of rotations, or does any valid rotation count suffice?
  3. Once all customers from the input array have arrived, does the wheel continue to rotate until all remaining queued customers have boarded and the queue is completely empty?
  4. Can the values in the arriving customers array be negative, or are they guaranteed to be non-negative integers?
  5. Is there an upper limit to the number of rotations we can perform after the last customer arrives, or is the simulation strictly bounded by the size of the array plus clearing the remaining queue?

Brute Force Solution

Approach

To find the maximum profit for operating the Centennial Wheel, the brute force approach simulates the entire day minute by minute while trying out every single possibility of boarding passengers. By tracking how much money is made at each potential stopping point, we can compare the financial outcome of every possible number of rotations.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first group of people arriving at the wheel and simulate them getting on during the first rotation.
  2. Calculate the money earned from these passengers minus the cost of running the wheel, and write down this profit.
  3. Next, let the wheel spin another round, bring in the next arriving group of people, and calculate the updated total profit.
  4. Continue this exact simulation step-by-step for every single time a group arrives and every time the wheel makes a full turn, until all arriving groups have been processed.
  5. Keep a running list of the total profit earned at the end of each possible number of rotations.
  6. Once the simulation finishes for all possible scenarios, look back at your list of profits.
  7. Pick the exact number of rotations that resulted in the highest amount of money made, and report that as your final answer.

Code Implementation

def minOperationsMaxProfit(customers, boarding_cost, running_cost):
    # Simulate minute by minute to track waiting customers and rolling profits accurately.
    waiting_customers = 0
    current_profit = 0
    maximum_profit = -1
    optimal_rotations = -1
    rotation_count = 0
    customer_index = 0

    while customer_index < len(customers) or waiting_customers > 0:
        if customer_index < len(customers):
            waiting_customers += customers[customer_index]
            customer_index += 1

        boarding_count = min(4, waiting_customers)
        waiting_customers -= boarding_count
        rotation_count += 1

        current_profit += (boarding_count * boarding_cost) - running_cost

        # Record new maximums to find the exact number of rotations yielding peak profit.
        if current_profit > maximum_profit:
            maximum_profit = current_profit
            optimal_rotations = rotation_count

    # Return the rotation count that achieved the highest profit, or negative one if none.
    if maximum_profit > 0:
        return optimal_rotations
    else:
        return -1

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the simulation of the Centennial Wheel, where n represents the number of elements in the customer arrival array. We iterate through each arriving group of customers, and once all groups are processed, the wheel may need up to 4 additional rotations to clear any remaining passengers in the queue. Because the total number of wheel rotations and simulation steps is bound by n plus a small constant of at most 4 extra turns, the total operations scale linearly. Therefore, the overall time complexity simplifies to O(n).
Space Complexity
O(1) – The simulation only maintains a few primitive integer variables to track the current profit, maximum profit, waiting customers, and optimal rotations. Because no auxiliary data structures, lists, or recursion stacks scale with the input size N (where N represents the number of arriving customer groups), the extra memory remains constant. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

To find the most profitable way to run the Centennial Wheel, we can simulate the process hour by hour while keeping track of how much money we are making. Since any leftover people waiting in line simply roll over to the next rotation, we just need to keep counting the boarding customers, calculate the running profit at each step, and remember the exact moment we reached our highest profit.

Here's how the algorithm would work step-by-step:

  1. Begin with no people waiting in line, no customers having boarded yet, no money earned, and keep note of the best profit seen so far as zero.
  2. Look at the first batch of arriving customers and add them to the total crowd currently waiting on the ground.
  3. Determine how many people from the waiting crowd can actually board the wheel right now, remembering that the wheel has a strict maximum capacity per turn.
  4. Subtract the boarding customers from the waiting crowd so only the leftover people remain on the ground for the next turn.
  5. Calculate the money earned during this rotation by multiplying the number of boarding customers by the ticket price, and then subtract the cost of operating the wheel for that turn.
  6. Add this turn profit to your running total of money, and if this new total is higher than your previous best profit, update your record to save this amount and note the current rotation number.
  7. Repeat the process of adding new arrivals, boarding passengers, paying operating costs, and calculating profits for subsequent turns until all arriving groups have shown up and the waiting crowd is completely gone.
  8. Finally, look back at your records and report the rotation number that gave you the highest profit, or if you never managed to make any money at all, report a negative outcome.

Code Implementation

class Solution:
    def minOperationsMaxProfit(self, customers: list[int], boarding_cost: int, running_cost: int) -> int:
        people_waiting_ground = 0
        total_boarded_customers = 0
        cumulative_profit = 0
        maximum_profit = 0
        optimal_rotation = -1
        rotation_counter = 0
        
        customer_index = 0
        total_arriving_groups = len(customers)
        
        while customer_index < total_arriving_groups or people_waiting_ground > 0:
            if customer_index < total_arriving_groups:
                people_waiting_ground += customers[customer_index]
                customer_index += 1
            
            current_boarding = min(4, people_waiting_ground)
            people_waiting_ground -= current_boarding
            total_boarded_customers += current_boarding
            
            rotation_profit = (current_boarding * boarding_cost) - running_cost
            cumulative_profit += rotation_profit
            rotation_counter += 1
            
            # We track the peak profit dynamically to ensure we record the optimal rotation moment.
            if cumulative_profit > maximum_profit:
                maximum_profit = cumulative_profit
                optimal_rotation = rotation_counter
        
        # If no profitable operation occurred, we must return negative one as specified by the rules.
        if maximum_profit <= 0:
            return -1
        
        return optimal_rotation

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the length of the customers array, denoted as n, which represents the hours new arrivals appear. In the worst case, the simulation continues for n turns plus an additional number of turns to clear out any remaining people waiting in line. Each turn executes a constant amount of arithmetic operations to update the waiting crowd, board passengers, and calculate profits. Therefore, the total operations scale linearly with n, which simplifies to O(n).
Space Complexity
O(1) – The simulation only maintains a few primitive scalar variables to track the waiting crowd, boarded customers, running profit, and best recorded profit. Because no dynamic data structures or recursive call stacks grow with the number of arriving customer batches denoted by N, the auxiliary space remains entirely constant. Therefore, the extra memory used does not scale with the input size.

Edge Cases

Customers array is empty at the start
How to Handle:
Return -1 immediately since no rotations can occur to generate profit.
High board cost relative to ticket price resulting in negative profits
How to Handle:
Track maximum profit and return -1 if the peak profit remains strictly less than zero after all customers are processed.
A massive trailing queue of customers requiring many extra rotations after the input array ends
How to Handle:
Continue simulating wheel rotations using batches of four until the waiting customer count drops to zero.
Zero arriving customers for all rotations
How to Handle:
The simulation will process zero boardings and correctly return -1 due to zero or negative total profit.
Extremely large numbers of arriving customers in the input array
How to Handle:
Use standard integer types and mathematical division to process waiting queues efficiently in O(N) time without timing out.
Multiple rotations yielding the exact same maximum profit value
How to Handle:
Stop at the earliest rotation that achieves this maximum profit as required by returning the minimum number of rotations.
Customer arrival values contain zeros interspersed with large groups
How to Handle:
The queue accurately retains waiting customers from prior high-arrival rotations to be boarded during zero-arrival rotation turns.
Profit peaks early and then continuously drops due to high operational costs
How to Handle:
Keep a running maximum profit tracker and record the rotation index whenever a strictly higher profit is achieved.