problem:2461. 长度为 K 子数组中的最大和
思路:相似题
Accode:
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
unordered_map<int, int> dict;
deque<int> deq;
int m = k;
long long sum = 0;
int len = nums.size();
long long ans = 0;
for (int i = 0; i < len; i++) {
if (deq.size() && i - deq.front() + 1 > k) {
dict[nums[deq.front()]]--;
if (dict[nums[deq.front()]] == 0)
dict.erase(nums[deq.front()]);
sum -= nums[deq.front()];
deq.pop_front();
}
deq.push_back(i);
dict[nums[i]]++;
sum += nums[i];
if (i + 1 >= k && dict.size() >= m) {
ans = max(ans, sum);
}
}
return ans;
}
};
时间复杂度:$o(n)$