#1599
Maximum Profit of Operating a Centennial Wheel
MediumArraySimulationSliding WindowGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a sliding window technique to efficiently calculate profits while keeping track of customers waiting and the number of rotations. This reduces the need for nested loops and allows us to find the maximum profit in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Initialize variables for total customers, current profit, maximum profit, and the number of rotations.
- 2Step 2: Use a sliding window to iterate through the customers array, updating the total customers and profit for each rotation.
- 3Step 3: If profit exceeds maximum profit, update the maximum profit and rotations.
- 4Step 4: If at any point the profit becomes negative, break out of the loop as further rotations will not help.
solution.py17 lines
1def maxProfit(customers, boardingCost, runningCost):
2 n = len(customers)
3 total_customers = 0
4 current_profit = 0
5 max_profit = float('-inf')
6 rotations = 0
7 for i in range(n):
8 total_customers += customers[i]
9 served = min(total_customers, 4)
10 total_customers -= served
11 current_profit = served * boardingCost - (i + 1) * runningCost
12 if current_profit > max_profit:
13 max_profit = current_profit
14 rotations = i + 1
15 if current_profit < 0:
16 break
17 return rotations if max_profit > 0 else -1ℹ
Complexity note: The time complexity is O(n) because we iterate through the customers array only once, maintaining a running total of customers and profit.
- 1The maximum number of customers that can board in one rotation is 4.
- 2Profit must be calculated carefully considering both boarding and running costs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.