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;
}
};
-
LIVE
Human Events Daily with Jack Posobiec
54 minutes agoHUMAN EVENTS DAILY WITH JACK POSOBIEC
1,203 watching -
LIVE
LindellTV
35 minutes agoMIKE LINDELL RESPONDS TO JIMMY KIMMEL "INDEFINITE SUSPENSION"
287 watching -
1:57:27
The Charlie Kirk Show
2 hours agoMegyn Kelly Remembers Charlie + Jimmy Kimmel Off the Air | 9.18.2025
147K57 -
LIVE
SternAmerican
23 hours agoElection Integrity Call – Thurs, Sept 18 · 2 PM EST | Featuring Rhode Island
68 watching -
4:22
Michael Heaver
2 hours agoLabour Face Brutal UK WIPEOUT
12 -
10:32
Faith Frontline
17 hours agoKenneth Copeland EXPOSED as America’s CREEPIEST Pastor Yet
612 -
4:33:50
Right Side Broadcasting Network
21 hours agoLIVE REPLAY: President Trump Holds a Press Conference with Prime Minister Keir Starmer - 9/18/25
52.8K38 -
1:01:35
The Rubin Report
3 hours agoJimmy Kimmel Humiliated as NY Post Exposes His Dark Reaction to Being Canceled
49.2K88 -
12:49
Clownfish TV
9 hours agoJimmy Kimmel Pulled OFF THE AIR for Charlie Kirk Comments?! | Clownfish TV
5.42K19 -
TheAlecLaceShow
2 hours agoJimmy Kimmel FIRED | ANTIFA Labeled Terrorist Org | Guest: Matt Palumbo | The Alec Lace Show
3.82K4