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
GritsGG
10 hours agoWin Streaking! Most Wins 3180+! 🔥
1,801 watching -
LIVE
This is the Ray Gaming
2 hours agoSunday Night LIVE | Rumble Premium Streamer
153 watching -
2:42:31
Barry Cunningham
8 hours agoPRESIDENT TRUMP IS SAVING AMERICA ONE DEAL AT A TIME! UNBELIEVABLE!
63.8K39 -
5:12:47
EricJohnPizzaArtist
5 days agoAwesome Sauce PIZZA ART LIVE Ep. #56: Bret “The Hitman” Hart Tribute with SoundBoardLord!
31.8K7 -
1:38:08
HELMETFIRE
3 hours ago🟢GAMING WITH FIRE EP4🟢RUMBLE TAKEOVER!🟢
10.9K -
LIVE
iCheapshot
4 hours agoCheap Plays Warzone Again? What!?
173 watching -
2:30:14
PandaSub2000
6 hours agoCHAOS & FURY | Episode 27: Attack Of The Cranks (Edited Replay)
12.9K1 -
LIVE
Spartan
2 hours agoSpartan - Pro Halo Player for OMiT | Ranked for a little bit
21 watching -
15:15
Adam Does Movies
1 day ago $3.00 earnedHappy Gilmore 2 - Movie Review
22.5K16 -
3:10:16
Toolman Tim
5 hours agoDOOM: The Dark Ages ALMOST DONE! | The Gaming Thinktank
8.49K