滑动窗口
1343:大小为k且平均值大于等于阈值的子数组数目
class Solution {
public:int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int ant=0;int q[100005],hh=0,tt=-1;int sum=0;for(int i=0;i<arr.size();i++){if(hh<=tt&&i-hh+1>k){sum-=q[hh];hh++;}q[++tt]=arr[i]; sum+=q[tt];if(i>=k-1&& sum/k>=threshold)ant++;}return ant;}
};
2090. 半径为 k 的子数组平均值
class Solution {
public:vector<int> getAverages(vector<int>& nums, int k) {vector<int> ans(nums.size(),-1);int q[100005],tt=-1,hh=0;long long ant=0;if(k==0)return nums;for(int i=0;i<nums.size();i++){if(hh<=tt && i-hh+1>2*k+1){ant-=q[hh];hh++;}q[++tt]=nums[i];ant+=q[tt];if(i>=2*k)ans[i-k]=ant/(2*k+1);} return ans;}
};
1052.爱生气的书店老板
class Solution {
public:int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {int ant=0; int ma=0 ,sum=0;int q[20000],hh=0,tt=-1;for(int i=0;i<grumpy.size();i++){int statu=grumpy[i];if(statu==0){sum+=customers[i];continue;}while(hh<=tt&&i-q[hh]+1>minutes){ant-=customers[q[hh]];hh++;}q[++tt]=i;ant+=customers[i];ma=max(ant,ma);}return sum+ma;}
};
2841. 几乎唯一子数组的最大和
class Solution {
public:long long maxSum(vector<int>& nums, int ma, int k) {unordered_map<int,int> m;long long sum=0,ant=0;for(int i=0;i<k-1;i++){sum+=nums[i];m[nums[i]]++;}for(int i=k-1;i<nums.size();i++){sum+=nums[i];m[nums[i]]++;if(m.size()>=ma)ant=max(ant,sum);sum-=nums[i-k+1];if(--m[nums[i-k+1]]==0)m.erase(nums[i-k+1]);}return ant;}
};
2461. 长度为 K 子数组中的最大和
class Solution {
public:long maximumSubarraySum(vector<int>& nums, int k) {long long ant=0,sum=0;unordered_map<int,int> m;for(int i=0;i<k-1;i++){sum+=nums[i];m[nums[i]]++;}for(int i=k-1;i<nums.size();i++){sum+=nums[i];m[nums[i]]++;if(m.size()==k)ant=max(ant,sum);sum-=nums[i-k+1];if(--m[nums[i-k+1]]==0)m.erase(nums[i-k+1]);}return ant;}
};
1423:可获得的最大点数
class Solution {
public:int maxScore(vector<int>& cardPoints, int k) {int l=cardPoints.size();long long zsum=0;for(int i=0;i<l;i++)zsum+=cardPoints[i];if(k==l)return zsum;int len=l-k;long long sum=0,ant=2000000000; for(int i=0;i<len-1;i++){sum+=cardPoints[i];}for(int i=len-1;i<l;i++){sum+=cardPoints[i];ant=min(ant,sum);sum-=cardPoints[i-len+1];}return zsum-ant;}
};