Premium Only Content

2461. Maximum Sum of Distinct Subarrays With Length K
You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:
The length of the subarray is k, and
All the elements of the subarray are distinct.
Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,5,4,2,9,9,9], k = 3
Output: 15
Explanation: The subarrays of nums with length 3 are:
- [1,5,4] which meets the requirements and has a sum of 10.
- [5,4,2] which meets the requirements and has a sum of 11.
- [4,2,9] which meets the requirements and has a sum of 15.
- [2,9,9] which does not meet the requirements because the element 9 is repeated.
- [9,9,9] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions
Example 2:
Input: nums = [4,4,4], k = 3
Output: 0
Explanation: The subarrays of nums with length 3 are:
- [4,4,4] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 105
#define ll long long
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
ll sum=0,ans=0;
int start=0,end=0,n=nums.size();
unordered_map<int,int> mp;
while(end<n){
int val = nums[end];
int lastindex = mp.count(val) ? mp[val] : -1;
while(start <= lastindex || end - start + 1>k){
sum -= nums[start];
start++;
}
mp[val] = end;
sum += nums[end];
if(end - start + 1 == k){
ans = max(ans,sum);
}
end++;
}
return ans;
}
};
-
11:04
Nate The Lawyer
3 days ago $3.10 earnedJudge, Mayor & 13 Democrats Arrested In Massive Mail-In Voter Fraud Scandal
7.97K30 -
50:15
daniellesmithab
1 day agoKick-Starting Careers for Young Albertans
8.44K -
39:01
Stephen Gardner
16 hours ago🔥This Will Leave You FURIOUS... What’s Really Going On?
62.8K127 -
19:33
DeVory Darkins
18 hours ago $10.20 earnedBREAKING: Charlie Kirk's shooter in custody after making chilling confession
33.7K147 -
2:12:43
TimcastIRL
11 hours agoErika Kirk Addresses Public After Charlie Kirk Assassination, Live Coverage | Timcast IRL
416K413 -
30:59
The Charlie Kirk Show
11 hours agoCharlie Kirk's beloved wife, Mrs. Erika Kirk addresses the Nation.
567K1.66K -
1:53:28
Man in America
19 hours agoLIVE: Assassin Arrested? Civil War? Are We Being Played?? | LET'S TALK
114K156 -
2:10:33
Badlands Media
16 hours agoOnlyLands Ep. 24: Processing Tragedy, Cancel Culture, and the Next Spark
77.4K30 -
2:27:53
TheSaltyCracker
11 hours agoGot Him ReeEEStream 9-12-25
296K403 -
52:11
Sarah Westall
13 hours agoBread and Circus Keeps you Financially Ignorant – Its Better for the Elites w/ Chris Russo
78.8K8