题目链接




Python3
方法: 模拟 ⟮O(n)、O(1)⟯
class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
res = -1
max_profit = total_profit = operations = rest = 0
for c in customers:
operations += 1
rest += c
temp = min(rest, 4)
rest -= temp
total_profit += boardingCost * temp - runningCost
if total_profit > max_profit:
max_profit = total_profit
res = operations
if rest == 0:
return res
if boardingCost * 4 - runningCost <= 0:
return res
if rest > 0:
t = rest // 4
total_profit += t * (boardingCost * 4 - runningCost)
operations += t
if total_profit > max_profit:
max_profit = total_profit
res = operations
rest = rest % 4
if rest > 0:
total_profit += boardingCost * rest - runningCost
if total_profit > max_profit:
operations += 1
res += 1
return res

C++
方法: 模拟 ⟮O(n)、O(1)⟯
class Solution {
public:
int minOperationsMaxProfit(vector<int>& customers, int boardingCost, int runningCost) {
int res = -1;
int max_profit = 0, total_profit = 0, operations = 0, rest = 0;
for (int c : customers){
++operations;
rest += c;
int temp = min(rest, 4);
rest -= temp;
total_profit += boardingCost * temp - runningCost;
if (total_profit > max_profit){
max_profit = total_profit;
res = operations;
}
}
if (rest == 0){
return res;
}
int profit_4 = boardingCost * 4 - runningCost;
if (profit_4 <= 0){
return res;
}
if (res > 0){
int t = rest / 4;
total_profit += t * profit_4;
operations += t;
if (total_profit > max_profit){
max_profit = total_profit;
res = operations;
}
rest = rest % 4;
if (rest > 0){
total_profit += boardingCost * rest - runningCost;
if (total_profit > max_profit){
++operations;
res += 1;
}
}
}
return res;
}
};