愛生氣的書店老闆

1.題目

今天,書店老闆有一家店打算試營業 customers.length 分鐘。每分鐘都有一些顧客(customers[i])會進入書店,全部這些顧客都會在那一分鐘結束後離開。c++

在某些時候,書店老闆會生氣。 若是書店老闆在第 i 分鐘生氣,那麼 grumpy[i] = 1,不然 grumpy[i] = 0。 當書店老闆生氣時,那一分鐘的顧客就會不滿意,不生氣則他們是滿意的。網絡

書店老闆知道一個祕密技巧,能抑制本身的情緒,可讓本身連續 X 分鐘不生氣,但卻只能使用一次。code

請你返回這一天營業下來,最多有多少客戶可以感到滿意的數量。leetcode

示例:get

輸入: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.io

提示:class

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

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。統計

2.解題思路(本身和官方解法同樣,只是本身代碼不夠簡潔)

咱們轉換一下咱們要找的東西,咱們要求最多地客戶可以感到滿意,那麼咱們就須要讓老闆把控制情緒的這個能力發揮到最大,也就是求X區間內老闆心情很差的時候進入書店的遊客總數最大,即咱們把X區間內全部grumpy爲1的值的下標對應的customers的值加起來最大,咱們就可讓感到滿意的顧客數量最大。di

長度是不變的,咱們能夠採用滑動窗口的解法來作,記錄這個窗口裏面老闆心情爲1的全部值的大小,統計出最大的數量,我我的的解法是記錄了老闆何時開始抑制心情,而後在從新求sum。官方解法是先求出老闆心情好的遊客的總數,而後再統計出區間X內最大的可抑制的遊客數目,加起來就是咱們須要的答案。

3.滑動窗口解法(本身)

class Solution {
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
    	int place = 0;//開始抑制本身情緒地位置
    	int max = 0;
    	int sum = 0;
    	int left = 0, right = left + X;
    	for(int i = left; i < right; i++) {
    		if(grumpy[i])
    			sum += customers[i];
    	}
    	max = sum;
    	while(right < customers.size()) {
    		if(grumpy[left])
    			sum -= customers[left];
    		left++;
    		if(grumpy[right])
    			sum += customers[right];
    		right++;
    		if(sum > max) {
    			max =sum;
    			place = left;
    		}
    	}
    	sum = 0;
    	for(int i = 0; i < customers.size(); i++) {
    		if(i >= place && i < place + X) {
    			sum += customers[i];
    		}
    		else {
    			if(grumpy[i] == 0)
    				sum += customers[i];
    		}
    	}
    	return sum;
    }
};

4.滑動窗口解法(官方)

class Solution {
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
        int total = 0;
        int n = customers.size();
        for (int i = 0; i < n; i++) {
            if (grumpy[i] == 0) {
                total += customers[i];
            }
        }
        int increase = 0;
        for (int i = 0; i < X; i++) {
            increase += customers[i] * grumpy[i];
        }
        int maxIncrease = increase;
        for (int i = X; i < n; i++) {
            increase = increase - customers[i - X] * grumpy[i - X] + customers[i] * grumpy[i];
            maxIncrease = max(maxIncrease, increase);
        }
        return total + maxIncrease;
    }
};

做者:LeetCode-Solution
連接:https://leetcode-cn.com/problems/grumpy-bookstore-owner/solution/ai-sheng-qi-de-shu-dian-lao-ban-by-leetc-dloq/
來源:力扣(LeetCode)
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索