今天,書店老板有一家店打算試營業 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.
代碼
class Solution {public int maxSatisfied(int[] customers, int[] grumpy, int X) {int n=customers.length,res=0,start=0;for(int i=0;i<n;i++)//計算老板不發火時候的人數以及初始區間{if(grumpy[i]==0)res+=customers[i];else if(i<X) start+=customers[i];}int l=0,r=X-1,pre=start;while (r+1<n){int temp=pre;//上一個區間的值r++;//移動區間if(grumpy[r]==1) temp+=customers[r];if(grumpy[l]==1) temp-=customers[l];l++;pre=temp;start= Math.max(start,temp);//最大滑動區間}return res+start;}
}