Back to Dashboard
Maximum Sum of Distinct Subarrays With Length K
MediumProblem Statement
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.
Examples
Example 1:
- Input:
nums = [1,5,4,2,9,9,9], k = 3 - Output:
15
Approach 1 Sliding Window:
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
var windowStart = 0;
long windowSum = 0;
long maxSum = Long.MIN_VALUE;
var set = new HashSet<Integer>();
for (int windowEnd = 0; windowEnd < nums.length; windowEnd ++) {
var val = nums[windowEnd];
//Shrinking Window Gradually until the Duplicate is GONE
while (set.contains(val)) {
set.remove(nums[windowStart]);
windowSum -= nums[windowStart];
windowStart ++;
}
set.add(val);
windowSum += val;
if (windowEnd - windowStart + 1 == k) {
maxSum = Math.max(maxSum, windowSum);
windowSum -= nums[windowStart];
set.remove(nums[windowStart]);
windowStart ++;
}
}
return maxSum == Long.MIN_VALUE
? 0
: maxSum;
}
}