algorithm-base/animation-simulation/数组篇/leetcode1052爱生气的书店老板.md

119 lines
5.1 KiB
Java
Raw Normal View History

2021-03-17 12:50:45 +00:00
2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
#### [1052. ](https://leetcode-cn.com/problems/grumpy-bookstore-owner/)
2021-03-17 12:50:45 +00:00
****
customers.length customers[i]
i grumpy[i] = 1 grumpy[i] = 0
X 使
> customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
> 16
3
= 1 + 1 + 1 + 1 + 7 + 5 = 16.
2021-03-17 11:49:19 +00:00
customer leftsum, winsum, rightsum
![](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/微信截图_20210223083057.1vns7wrs2z0.png)
winsum grumpy[i] 0 1, K
leftsum grumpy[i] == 0 grumpy[i] == 0
rightsum win leftsum rightsum
![](https://cdn.jsdelivr.net/gh/tan45du/test1@master/20210122/微信截图_20210223084549.5ht4nytfe1o0.png)
leftsum grumpy[i] == 1 grumpy[i] == 0
rightsum grumpy[i] == 0 rightsum -= grumpy[i]
winsum winsum , customer[left-1]left
Java Code:
2021-03-17 11:49:19 +00:00
```java
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int winsum = 0;
int rightsum = 0;
int len = customers.length;
//右区间的值
for (int i = X; i < len; ++i) {
if (grumpy[i] == 0) {
rightsum += customers[i];
}
}
//窗口的值
for (int i = 0; i < X; ++i) {
winsum += customers[i];
}
int leftsum = 0;
//窗口左边缘
int left = 1;
//窗口右边缘
int right = X;
int maxcustomer = winsum + leftsum + rightsum;
while (right < customers.length) {
//重新计算左区间的值,也可以用 customer 值和 grumpy 值相乘获得
if (grumpy[left-1] == 0) {
leftsum += customers[left-1];
}
//重新计算右区间值
if (grumpy[right] == 0) {
rightsum -= customers[right];
}
//窗口值
winsum = winsum - customers[left-1] + customers[right];
//保留最大值
maxcustomer = Math.max(maxcustomer,winsum+leftsum+rightsum);
//移动窗口
left++;
right++;
}
return maxcustomer;
}
}
```
Python3 Code:
```py
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
t = ans = sum(customers[:X]) + sum(map(lambda x: customers[X+x[0]] if x[1] == 0 else 0, enumerate(grumpy[X:])))
for j in range(X, len(customers)):
t += customers[j] * grumpy[j] - customers[j-X] * grumpy[j-X]
ans = max(ans, t)
return ans
```
2021-03-20 07:48:03 +00:00