Leetcode-爱生气的书店老板(1052)

题目描述:
今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。
在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。
书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。
请你返回这一天营业下来,最多有多少客户能够感到满意的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner

思路:
看完题目,首先要读懂题意。
长度:customers.length
每分钟顾客(人数):customers[i]
老板个人小脾气上头:grumpy[i]=0,不生气,grumpy[i]=1,生气
秘密绝招: X 分钟不生气
那要求解的其实就是个滑动窗口的最大值,就是说原本老板可以赚多少,用了大招之后怎么最大程度达到利益最大化。
1:原本可以达到多少满意的数量

for(int i = 0;i<n;i++) 
	if(grumpy[i] == 0)
		total += cumstomers[i]

total 就是原本总共可以达到的满意的数量
2:使用秘密绝招后的增益

# 当前的增加的满意度
for(int i = 0; i < X; i++) curValue += customers[i] * grumpy[i];
int increseValue = curValue;
# 滑动窗口,比较滑动后的值和之前的值哪个更大,取最大值,然后继续滑动,比较,最后找到最大的那个滑动区间
for(int i = X; i < n; i++){
	curValue += customers[i] * grumpy[i] - customers[i-X] * grumpy[i-X];
	increseValue = max(increseValue,curValue); 
}

3:将原本的满意度和使用过秘密绝招后的满意度相加就是老板可以达到的最大满意度

代码

int maxSatisfied(int* customers, int customersSize, int* grumpy, int grumpySize, int X){
    int total = 0, n = customersSize;
    int curValue = 0;
    for(int i = 0; i < n; ++i){
        if(grumpy[i] == 0){
            total += customers[i];
        }
    }      
    for(int i = 0; i < X; ++i) 
        curValue += customers[i] * grumpy[i];
    int increseValue = curValue;
    for(int i = X;i < n; ++i){
        curValue += customers[i] * grumpy[i] - customers[i-X] * grumpy[i-X];
        increseValue = fmax(curValue, increseValue);
    }
    return increseValue + total;
}

Python 代码

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        n = len(customers)
        sum_ = 0
        #使用绝招后的增益
        for i in range(X):
            sum_ =sum_ + customers[i] * grumpy[i]
        res = sum_
        for i in range(X,n):
            sum_ = sum_ +  customers[i] * grumpy[i] - customers[i-X] * grumpy[i-X]
            res = max(res,sum_)
         # 原本应该有的顾客数
        for i in range(n):
            res = res + customers[i] * (1 - grumpy[i])
        return  res

如果觉得有帮助的话,麻烦点赞和关注下,谢谢~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值