LeetCode-1052. Grumpy Bookstore Owner [Medium]-Analysis and Code (Java)

LeetCode-1052. Angry Bookstore Owner [Grumpy Bookstore Owner] [Medium]-Analysis and Code [Java]

1. Topic

Today, the bookstore owner has a store intending to open customers.length minutes in trial. Every minute some customers (customers[i]) will enter the bookstore, and all these customers will leave after that minute is over.
At some point, the bookstore owner will get angry. If the bookstore owner is angry at the i-th minute, then grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is angry, the customers at that minute will be dissatisfied, and if they are not angry, they will be satisfied.
The bookstore owner knows a secret technique that can suppress his emotions and keep himself from getting angry for X minutes, but he can only use it once.
Please return to this day of business, the maximum number of customers that can be satisfied.

Example:

输入: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.

prompt:

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/grumpy-bookstore-owner
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Sliding window

(1) Thinking

On the one hand, when the bookstore owner is not angry, determine the number of satisfied customers; on the other hand, design a sliding window with a length of X. In the statistics window, the maximum number of unsatisfied customers caused by the bookstore owner’s anger is the sum of the two. Solution.

(2) Code

class Solution {
    
    
    public int maxSatisfied(int[] customers, int[] grumpy, int X) {
    
    
        int n = customers.length, custNum = 0, dec = 0; 
        for (int i = 0; i < X; i++) {
    
         
            if (grumpy[i] == 1)
                dec += customers[i];
            else
                custNum += customers[i];//统计顾客满意数
        }
        int decMax = dec;//减小的最大损失
        for (int i = X; i < n; i++) {
    
    
            if (grumpy[i - X] == 1)//移出窗口的不满意顾客数
                dec -= customers[i - X];
            if (grumpy[i] == 1)
                dec += customers[i];//移入窗口的不满意顾客数
            else
                custNum += customers[i];//继续统计顾客满意数
            decMax = Math.max(decMax, dec);
        }
        return custNum + decMax;
    }
}

(3) Results

Execution time: 4 ms, beating 39.80% of users
in all Java submissions ; memory consumption: 40.7 MB, beating 87.15% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/114235057