Skip to content

Commit 541caa6

Browse files
committed
Time: 45 ms (52.96%), Space: 58.9 MB (36.28%) - LeetHub
1 parent 1262b96 commit 541caa6

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

2461-maximum-sum-of-distinct-subarrays-with-length-k/2461-maximum-sum-of-distinct-subarrays-with-length-k.java

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,28 @@ class Solution {
22
public long maximumSubarraySum(int[] nums, int k) {
33
//Sliding window ::
44
int n = nums.length;
5-
Set<Integer> set = new HashSet<>();
5+
HashMap<Integer, Integer> map = new HashMap<>();
66
int start =0;
77
int end =0;
88
long sum=0, ans =0;
9-
while(end<n){
10-
while (set.contains(nums[end]) || set.size() == k) {
11-
set.remove(nums[start]);
12-
sum -= nums[start++];
9+
while(end<n){
10+
sum+=nums[end];
11+
map.put(nums[end] , map.getOrDefault(nums[end],0)+1);
12+
13+
while(end-start+1>k){
14+
sum-=nums[start];
15+
map.put(nums[start],map.get(nums[start])-1);
16+
if(map.get(nums[start])==0){
17+
map.remove(nums[start]);
18+
}
19+
20+
start++;
1321
}
14-
sum += nums[end];
15-
set.add(nums[end]);
16-
if (set.size() == k) {
17-
ans = Math.max(ans, sum);
22+
23+
if(end-start+1 == k && map.size()==k){
24+
ans = Math.max(ans,sum);
1825
}
26+
1927
end++;
2028
}
2129
return ans;

0 commit comments

Comments
 (0)