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;
}
};
-
3:58:54
SavageJayGatsby
6 hours ago🎃 Friend Friday – Halloween Edition! 👻🕷️
15.5K1 -
16:16
Robbi On The Record
12 days ago $16.47 earnedThe Dark History of Halloween | What You Should Know
52.6K45 -
58:18
Flyover Conservatives
23 hours agoThe Truth About Halloween that You DIDN’T Know - Holiday Special - Historian Bill Federer | FOC SPECIAL Show
30.3K2 -
3:10:46
Ellie_roe
4 hours agoEllie and Errys Halloween Spooktacular || Random Horror Games
11K -
50:27
Sarah Westall
6 hours agoBig Banks Caught Rigging Market, IMF tells World to “Buckle Up” w/ Andy Schectman
25.3K5 -
13:54
Degenerate Jay
12 hours ago $0.91 earned5 Best Superhero Movies To Watch On Halloween
11.1K2 -
59:03
NAG Podcast
5 hours agoSarah Fields: BOLDTALK W/Angela Belcamino
17.7K5 -
1:21:41
Glenn Greenwald
8 hours agoGlenn Takes Your Questions: On the Argentina Bailout, Money in Politics, and More | SYSTEM UPDATE #541
76.8K38 -
3:10:08
Barry Cunningham
5 hours agoPRESIDENT TRUMP TO USE NUCLEAR OPTION? FOOD STAMPS END! | SHUTDOWN DAY 31
45.2K31 -
1:06:56
BonginoReport
13 hours agoThe Battle Between Good & Evil w/ Demonologist Rick Hansen - Hayley Caronia (Ep.168)
97.9K33