Let's make this one less mysterious. For 1599. Maximum Profit of Operating a Centennial Wheel, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are minOperationsMaxProfit.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 276 ms, faster than 82.02% of C++ online submissions for Maximum Profit of Operating a Centennial Wheel.
02//Memory Usage: 81.7 MB, less than 13.45% of C++ online submissions for Maximum Profit of Operating a Centennial Wheel.
03class Solution {
04public:
05 int minOperationsMaxProfit(vector<int>& customers, int boardingCost, int runningCost) {
06 int max_time, max_profit = INT_MIN;
07 int cur = 0;
08 int remain = 0;
09 int n = customers.size();
10
11 int time = 1;
12
13 for(time = 1; time <= n; ++time){
14 int board = min(4, remain+customers[time-1]);
15 cur += board * boardingCost - runningCost;
16
17 if(cur > max_profit){
18 max_profit = cur;
19 max_time = time;
20 }
21
22 remain += (customers[time-1] - board);
23 }
24
25 for(; remain; ++time){
26 int board = min(4, remain);
27 cur += board * boardingCost - runningCost;
28
29 if(cur > max_profit){
30 max_profit = cur;
31 max_time = time;
32 }
33
34 remain -= board;
35 }
36
37 return (max_profit < 0) ? -1 : max_time;
38 }
39};
Cost