leetcode_1052. Grumpy Bookstore Owner

1052. Grumpy Bookstore Owner

https://leetcode.com/problems/grumpy-bookstore-owner/

题意:每个时刻i会有customer[i]个顾客进店,在i时刻店主的情绪是grumpy[i],若grumpy[i]==1则店主脾气暴躁,那么顾客会不满意,否则顾客讲感到满意,店主会一个技巧保证连续X时间内不暴躁,但他只能使用一次。问最多可以有多少顾客满意。


解法:找到一个连续X时间段,使用技巧后,得到的收益最大。计算前缀和,然后依次遍历所有连续X时间段,找到使用技巧能使最多的顾客从不满意变为满意。

class Solution
{
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X)
    {
        vector<int> presum(grumpy.size());
        if(grumpy[0]==1)
            presum[0]=customers[0];
        for(int i=1;i<grumpy.size();i++)
        {
            presum[i]=grumpy[i]==1?(presum[i-1]+customers[i]):presum[i-1];
        }
        int max_sum=presum[X-1],last_pos=X-1;
        for(int i=X;i<grumpy.size();i++)
        {
            int st_pos = i-X+1;
            if(max_sum<presum[i]-presum[st_pos-1])
            {
                max_sum=presum[i]-presum[st_pos-1];
                last_pos=i;
            }
        }
        int res=0;
        for(int i=0;i<grumpy.size();i++)
        {
            if(grumpy[i]==0)
                res+=customers[i];
            else if(i>=last_pos-X+1&&i<=last_pos)
                res+=customers[i];
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/jasonlixuetao/p/10925898.html