[leetcode/lintcode 题解] 爱生气的书店老板

290 阅读1分钟

有一个书店,在接下来的n天中的第i天会有customer[i]个顾客到来,并且在这一天结束后离开。

但是书店老板的脾气时好时坏,我们用一个数组grumpy表示他每一天的脾气好坏,若 grumpy[i]=1, 则表示第i天老板的脾气很不好;若grumpy[i]=0, 则表示第i天老板的脾气很好。

若某一天书店老板的脾气不好,则会导致所有当天来的所有顾客会给书店差评。但如果某一天脾气好,那么当天所有顾客都会给书店好评。

老板想要尽量增加给书店好评的人数数量,想了一个方法。他可以保持连续X天的好脾气。但这个方法只能使用一次。

那么在这n天这个书店最多能有多少人离开时给书店好评?

在线评测地址:lintcode领扣

样例
输入:
[1,0,1,2,1,1,7,5]
[0,1,0,1,0,1,0,1]
3
输出: 16
Explanation: 书店老板在最后3天保持好脾气。
感到满意的最大客户数量 = 1 + 1 + 1 + 1 + 7 + 5 = 16.

【题解】

滑动窗口求解,滑动

public class Solution {
    /**
     * @param customers: the number of customers
     * @param grumpy: the owner's temper every day
     * @param X: X days
     * @return: calc the max satisfied customers
     */
    public int maxSatisfied(int[] customers, int[] grumpy, int X) {
        // write your code here
        int n = customers.length;
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += customers[i] * (1 - grumpy[i]);
        int cur = 0;
        for (int i = 0; i < X; i++)
            cur += customers[i] * grumpy[i];
        int maxx = cur;
        for (int i = X; i < n; i++){
            cur = cur + customers[i] * grumpy[i] - customers[i - X] * grumpy[i - X];
            maxx = Math.max(maxx, cur);
        }
        return sum + maxx;
    }
}

更多题解参见:leetcode/lintcode题解