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;
}
};
-
1:07:59
NotTheBee
1 day agoOur Memories Of Charlie Kirk And What This Means For The Country
21.3K21 -
DVR
The Rubin Report
1 hour agoListen to the Fear in Whoopi Goldberg’s Voice on 'The View' as She Gives a Chilling Warning
39.5K27 -
LIVE
The Mel K Show
1 hour agoMORNINGS WITH MEL K - Constitution Incompatible with Globalist Goals 9-16-25
585 watching -
LIVE
Grant Stinchfield
1 hour agoRFK Jr. Speaks Out: The Pain of Assassination & the Loss of Charlie Kirk
86 watching -
1:59:33
Benny Johnson
2 hours agoKash Patel Testifying LIVE Now on Charlie Kirk Assassination, Trump to Declare Antifa TERRORISTS?!
72.5K43 -
2:07:38
Timcast
3 hours ago🚨LIVE: Kash Patel Testifies Over Charlie Kirk Assassination In Senate | Tim Pool
82.9K54 -
LIVE
Trumpet Daily
47 minutes agoTrumpet Daily LIVE | Sept. 16, 2025
457 watching -
LIVE
The Shannon Joy Show
1 hour agoTrojan Horse Trump Pushing ‘Worse Than Biden’ Speech Control Using Kirk Killing. Guest Brett Miller
241 watching -
1:01:35
VINCE
3 hours agoThe Left's 'Malignant' Violence Problem | Episode 126 - 09/16/25
191K113 -
LIVE
LFA TV
6 hours agoLFA TV ALL DAY STREAM - TUESDAY 9/16/25
4,398 watching