-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathEquivalentSubArrays.java
38 lines (29 loc) · 1.05 KB
/
EquivalentSubArrays.java
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
32
33
34
35
36
37
38
class Solution {
// Method to calculate distinct sub-array
static int countDistinctSubarray(int arr[], int n) {
HashSet<Integer> set = new HashSet<>();
for(int a: arr) set.add(a);
HashMap<Integer, Integer> map = new HashMap<>();
int ue = set.size(), i=-1, j=-1;
int ans = 0;
while(true) {
boolean f1 = false, f2 = false;
// Acquire
while(i < arr.length-1 && map.size() != ue) {
f1 = true;
i++;
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
// Collect and Release
while(j < i && map.size() == ue) {
f2 = true;
j++;
ans += n-i;
if(map.get(arr[j]) == 1) map.remove(arr[j]);
else map.put(arr[j], map.get(arr[j])-1);
}
if(!f1 && !f2) break;
}
return ans;
}
}