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;
}
};
-
2:11:52
Side Scrollers Podcast
18 hours agoYouTube ADMITS BLATANT Censorship + California Wants to FINE “Hate Speech” + More | Side Scrollers
70.8K10 -
15:18
GritsGG
14 hours agoSweaty Quads w/ Bobby Poff!
12.8K2 -
17:11
Nikko Ortiz
1 day agoIs Poverty Your Fault?
33.4K35 -
1:25:15
The HotSeat
1 day agoIn Less Than Two Weeks, Here We Are Again.....
19.4K15 -
12:55
The Pascal Show
13 hours ago $3.23 earned'THAT'S HIS GIRLFRIEND!' D4vd's Friends Speak Out Revealing They Thought Celeste Was His Girlfriend!
10.2K1 -
LIVE
Lofi Girl
2 years agoSynthwave Radio 🌌 - beats to chill/game to
259 watching -
33:02
DeVory Darkins
8 hours ago $35.86 earnedComey INDICTED by grand jury in shocking announcement by DOJ as Trump claims MAJOR VICTORY
43.5K100 -
2:06:23
Inverted World Live
9 hours agoEpstein Worked for CIA According to OMG Reporting | Ep. 114
139K41 -
3:14:39
TimcastIRL
9 hours agoTrump DOJ Indicts James Comey, The ARRESTS Have BEGUN | Timcast IRL
329K403 -
7:54:14
SpartakusLIVE
11 hours ago#1 Hulking MASS squashes NOOBS for viewers’ DELIGHT
74.9K2