当前位置: 代码迷 >> 综合 >> 1052. Grumpy Bookstore Owner**
  详细解决方案

1052. Grumpy Bookstore Owner**

热度:5   发布时间:2024-01-25 15:53:41.0

1052. Grumpy Bookstore Owner**

https://leetcode.com/problems/grumpy-bookstore-owner/

题目描述

Today, the bookstore owner has a store open for customers.length minutes. Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.

On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.

Return the maximum number of customers that can be satisfied throughout the day.

Example 1:

Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. 
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

Note:

  • 1 <= X <= customers.length == grumpy.length <= 20000
  • 0 <= customers[i] <= 1000
  • 0 <= grumpy[i] <= 1

C++ 实现 1

滑动窗口. 统计在大小为 X 的窗口中, 有多少顾客刚好处在店主脾气不好的时刻, 即 grumpy[i] == 1. 其中 grumpy[i] == 0 对应的顾客始终是满意的, 使用 base 来统计. 而对于那些 grumpy[i] == 1 的顾客, 只有在他们刚好在滑动窗口中, 才能满意, 用 new_satisfied 统计在滑动窗口中新满意的顾客, 在窗口滑动过程中使用 max_satisfied 来记录最大值. 最后返回 base + max_satisfied.

class Solution {
public:int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {int res = 0, base = 0, new_satisfied = 0, max_satisfied = 0;for (int i = 0; i < customers.size(); ++ i) {if (grumpy[i] == 0) base += customers[i];else new_satisfied += customers[i];if (i + 1 > X) { // 如果 nums[0...i] 范围内的数据个数大于 Xnew_satisfied -= grumpy[i - X] * customers[i - X];}max_satisfied = std::max(max_satisfied, new_satisfied);}return base + max_satisfied;}
};
  相关解决方案