-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumOfDistinctArr.java
More file actions
31 lines (30 loc) · 883 Bytes
/
Copy pathMaxSumOfDistinctArr.java
File metadata and controls
31 lines (30 loc) · 883 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.HashMap;
public class MaxSumOfDistinctArr {
public long maximumSubarraySum(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
int i = 0;
int j = 0;
long sum = 0;
long ans = 0;
while (j < nums.length) {
sum += nums[j];
map.put(nums[j], map.getOrDefault(nums[j], 0) + 1);
if (j - i + 1 < k) {
j++;
}
else if (j - i + 1 == k) {
if (map.size() == k) {
ans = Math.max(ans, sum);
}
sum -= nums[i];
map.put(nums[i], map.get(nums[i]) - 1);
if (map.get(nums[i]) == 0) {
map.remove(nums[i]);
}
i++;
j++;
}
}
return ans;
}
}