website/content/ChapterFour/1000~1099/1052.Grumpy-Bookstore-Owner.md
Today, the bookstore owner has a store open for customers.lengthminutes. 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 <= 200000 <= customers[i] <= 10000 <= grumpy[i] <= 1今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。请你返回这一天营业下来,最多有多少客户能够感到满意的数量。
提示:
customer0 专门记录脾气数组中为 0 的对应的价值,累加起来。因为不管怎么改变,为 0 的永远为 0,唯一变化的是 1 变成 0 。用 customer1 专门记录脾气数组中为 1 的对应的价值。在窗口滑动过程中找到 customer1 的最大值。最终要求的最大值就是 customer0 + maxCustomer1。
package leetcode
// 解法一 滑动窗口优化版
func maxSatisfied(customers []int, grumpy []int, X int) int {
customer0, customer1, maxCustomer1, left, right := 0, 0, 0, 0, 0
for ; right < len(customers); right++ {
if grumpy[right] == 0 {
customer0 += customers[right]
} else {
customer1 += customers[right]
for right-left+1 > X {
if grumpy[left] == 1 {
customer1 -= customers[left]
}
left++
}
if customer1 > maxCustomer1 {
maxCustomer1 = customer1
}
}
}
return maxCustomer1 + customer0
}
// 解法二 滑动窗口暴力版
func maxSatisfied1(customers []int, grumpy []int, X int) int {
left, right, res := 0, -1, 0
for left < len(customers) {
if right+1 < len(customers) && right-left < X-1 {
right++
} else {
if right-left+1 == X {
res = max(res, sumSatisfied(customers, grumpy, left, right))
}
left++
}
}
return res
}
func sumSatisfied(customers []int, grumpy []int, start, end int) int {
sum := 0
for i := 0; i < len(customers); i++ {
if i < start || i > end {
if grumpy[i] == 0 {
sum += customers[i]
}
} else {
sum += customers[i]
}
}
return sum
}