Skip to content

Commit 61b6d74

Browse files
authored
Create Maximum Sum of Distinct Subarrays With Length K.cpp
1 parent bb03300 commit 61b6d74

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//2461. Maximum Sum of Distinct Subarrays With Length K
2+
class Solution
3+
{
4+
public:
5+
long long maximumSubarraySum(vector<int> &nums, int k)
6+
{
7+
int n=nums.size();
8+
long long sum=0,maxo=0;
9+
10+
map<int,int> check;
11+
for(int i=0;i<k-1;i++){
12+
sum+=nums[i];
13+
check[nums[i]]++;
14+
}
15+
for(int i=k-1;i<n;i++){
16+
check[nums[i]]++;
17+
sum+=nums[i];
18+
if(check.size()==k){
19+
maxo=max(maxo,sum);
20+
}
21+
if(check[nums[i-k+1]]==1){
22+
check.erase(nums[i-k+1]);
23+
}
24+
else{
25+
check[nums[i-k+1]]--;
26+
}
27+
sum-=nums[i-k+1];
28+
}
29+
return maxo;
30+
}
31+
};

0 commit comments

Comments
 (0)