跳到主要内容

1052.爱生气的书店老板

链接:1052.爱生气的书店老板
难度:Medium
标签:数组、滑动窗口
简介:今天,书店老板有一家店打算试营业  customers.length  分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。请你返回这一天营业下来,最多有多少客户能够感到满意的数量。

题解 1 - typescript

  • 编辑时间:2021-02-23
  • 执行用时:104ms
  • 内存消耗:44.3MB
  • 编程语言:typescript
  • 解法介绍:读取范围内生气的值的最大值。
function maxSatisfied(customers: number[], grumpy: number[], X: number): number {
const _sum = (arr: number[]) => arr.reduce((total, cur) => total + cur, 0);
if (X === 0) return _sum(customers.filter((_, i) => grumpy[i]));
if (grumpy.every(v => !v)) return _sum(customers);
const len = customers.length;
let l = 0;
let r = X - 1;
let sum = _sum(customers.slice(0, X).filter((_, i) => grumpy[i]));
let maxSum = sum;
while (r < len - 1) {
if (grumpy[++r]) sum += customers[r];
if (grumpy[l]) sum -= customers[l];
l++;
maxSum = Math.max(maxSum, sum);
}
return maxSum + _sum(customers.filter((_, i) => !grumpy[i]));
}

题解 2 - python

  • 编辑时间:2024-04-23
  • 执行用时:58ms
  • 内存消耗:18.13MB
  • 编程语言:python
  • 解法介绍:滑动窗口。
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
n = len(customers)
res = cur = sum(customers[i] for i in range(n) if not grumpy[i] or i < minutes)
for i in range(minutes, n):
if grumpy[i - minutes]: cur -= customers[i - minutes]
if grumpy[i]: cur += customers[i]
res = max(res, cur)
return res