Untitled
unknown
plain_text
a year ago
1.2 kB
5
Indexable
class Solution {
public long maximumSubarraySum(int[] nums, int k) {
// Edge case: if k is larger than array length, return 0
if (k > nums.length) {
return 0;
}
// Use a HashSet to track elements in current window
Set<Integer> set = new HashSet<>();
// Initialize first window of size k
long currentSum = 0;
int i = 0,j=0;
while(j<k)
{
currentSum += nums[i];
set.add(nums[i]);
j++;
}
// Initialize maxSum
long maxSum = (set.size() == k) ? currentSum : 0;
// Slide the window
while(j<n) {
// Remove leftmost element from window
set.remove(nums[i]);
currentSum -= nums[i];
// Add new element to window
currentSum += nums[j];
set.add(nums[j]);
// Update maxSum if current window has all distinct elements
if (set.size() == k) {
maxSum = Math.max(maxSum, currentSum);
}
}
return maxSum;
}
}Editor is loading...
Leave a Comment