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
Wendy Bell Radio
4 hours agoPet Talk With The Pet Doc
917 watching -
30:58
SouthernbelleReacts
2 days agoWe Didn’t Expect That Ending… ‘Welcome to Derry’ S1 E1 Reaction
2.51K -
13:51
True Crime | Unsolved Cases | Mysterious Stories
4 days ago $0.15 earned7 Real Life Heroes Caught on Camera (Remastered Audio)
5K -
LIVE
Total Horse Channel
10 hours ago2025 IRCHA Derby & Horse Show - November 1st
29 watching -
4:19
PistonPop-TV
6 days agoThe 4E-FTE: Toyota’s Smallest Turbo Monster
3.08K -
43:07
WanderingWithWine
5 days ago $0.04 earned5 Dreamy Italian Houses You Can Own Now! Homes for Sale in Italy
3.68K2 -
LIVE
Spartan
19 hours agoFirst playthrough of First Berserker Khazan
284 watching -
28:01
Living Your Wellness Life
2 days agoTrain Your Hormones
6.54K -
43:28
The Heidi St. John Podcast
1 day agoFan Mail Friday: Faith Over Fear and Finding Strength in Every Season
3.46K -
1:05:30
SGT Report
1 day agoTHE HORRIBLE TRUTH ABOUT EVERYTHING -- Harley Schlanger
45.2K86