-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCountTriplets.java
49 lines (37 loc) · 1.67 KB
/
CountTriplets.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
39
40
41
42
43
44
45
46
47
48
49
/*https://www.hackerrank.com/challenges/count-triplets-1/*/
public class Solution {
// Complete the countTriplets function below.
static long countTriplets(List<Long> arr, long r) {
Map<Long, Long> potential = new HashMap<>();
Map<Long, Long> counter = new HashMap<>();
long count = 0;
for (int i = 0; i < arr.size(); i++) {
long a = arr.get(i);
long key = a / r;
if (counter.containsKey(key) && a % r == 0) {
count += counter.get(key);
}
if (potential.containsKey(key) && a % r == 0) {
long c = potential.get(key);
counter.put(a, counter.getOrDefault(a, 0L) + c);
}
potential.put(a, potential.getOrDefault(a, 0L) + 1); // Every number can be the start of a triplet.
}
return count;
}
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nr = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(nr[0]);
long r = Long.parseLong(nr[1]);
List<Long> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Long::parseLong)
.collect(toList());
long ans = countTriplets(arr, r);
bufferedWriter.write(String.valueOf(ans));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}