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;
}
};
-
1:35:37
Man in America
12 hours agoThe Forbidden Medicine of Light: Why is Big Pharma HIDING This From Us?
49.7K12 -
2:35:13
BlackDiamondGunsandGear
5 hours agoAFTER HOURS ARMORY / BUILDING GUNS ARE ILLEGAL? / Marine Gun Builder RETURNS!!
13.5K2 -
2:05:19
Damysus Gaming
5 hours agoARC Raiders - SERVER SLAM TIME!!!! LFG!!!
25.1K -
1:04:10
The Connect: With Johnny Mitchell
8 hours ago $3.33 earnedTucker Carlson's INSANE Take On Civil War In America, Calls For Fascism
18.6K39 -
2:35:14
DLDAfterDark
6 hours ago $3.30 earnedThe Return of Marine Gun Builder? MGB, DLD, BDG&G After Hours Armory
26K3 -
28:39
Afshin Rattansi's Going Underground
1 day agoDonald Trump’s Gaza Peace Plan: A Pivotal Moment or Farce? (Palestinian Deputy Foreign Minister)
27.4K6 -
3:31:29
SavageJayGatsby
7 hours ago🔥 Spicy Saturday – Let's Play: Prison Life 2🔥
45K2 -
4:34:18
cosmicvandenim
14 hours agoCOSMIC VAN DENIM | WARZONE HORROR
18.8K1 -
29:09
Stephen Gardner
11 hours ago🚨Trump DECLARES WAR on TERRORIST LEFT!
31.3K62 -
4:16:00
NellieBean
6 hours ago🔴 Lost Girl looks for Lost Village
9.48K