【LeetCode】1599. 经营摩天轮的最大利润

70 阅读1分钟

题目链接

image.png

image.png

image.png

image.png

Python3

方法: 模拟 O(n)O(1)\lgroup O(n)、O(1) \rgroup

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  # 必须在新游客到来前轮转 i 次
            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 

        # 摩天轮 必须至少转 len(customers) 次【所以每次应塞上尽量多的游客】, 后面是否还转无限制,不管是否还有游客
        if boardingCost * 4 - runningCost <= 0:  # 转一次 没有利润, 不转。
            return res 


        # 有利润  且 还有游客
        if rest > 0:
            t = rest // 4  # 坐满 4 个 的次数
            total_profit += t *  (boardingCost * 4 - runningCost)
            operations += t 
            if total_profit > max_profit:
                max_profit = total_profit
                res = operations

            # 剩余 游客 不足 4 人, 根据总利润 确定是否 要 加一轮
            rest = rest % 4
            if rest > 0:
                total_profit += boardingCost * rest - runningCost
                if total_profit > max_profit:
                    operations += 1
                    res += 1
        return res  

image.png

C++

方法: 模拟 O(n)O(1)\lgroup O(n)、O(1) \rgroup

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;
    }
};