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;
}
};
-
7:41
Adam Does Movies
15 hours ago $8.06 earnedDaredevil: Born Again Review - Does Disney Do The Show Justice?
39.9K5 -
5:06
Tundra Tactical
16 hours ago $3.00 earnedPam Bondi MUST Stop ATF's Zero Tolerance Policy NOW!
17.8K6 -
18:38
The Lou Holtz Show
20 hours agoLou Holtz: "Trump Stands for America—And He Means It!" | Ukraine, Pete Rose & Common Sense 🇺🇸
32.2K5 -
3:54
Randi Hipper
20 hours ago$100,000 BITCOIN COMING! HERE'S WHY
20.5K3 -
9:34
ariellescarcella
13 hours ago"Born This Way Is A Lie" : Religious Debate
29.9K10 -
LIVE
Matt Kohrs
9 hours ago🔴[LIVE TRADING] Time To Buy The Stock Market Dip?! || The MK Show
1,100 watching -
36:20
BonginoReport
3 hours agoJoe Rogan Brings Back Pizzagate (Ep.154) - 03/06/2025
25K26 -
LIVE
Wendy Bell Radio
5 hours agoStranded & Abandoned By The Democrat Party
12,915 watching -
6:05:13
Akademiks
17 hours agoDay 1/30. Drake Drops lawsuit vs iHeartMedia? Offset and Cardi Calls it Quits. 50 v Jim Jones?
218K13 -
2:55:11
TimcastIRL
14 hours agoDemocrat TANTRUM At Trump Speech BACKFIRES, Trump Polls UP, Dems UNDER FIRE w/67Kevin | Timcast IRL
266K136