|
| 1 | +// https://www.hackerrank.com/challenges/beautiful-triplets/problem |
| 2 | + |
| 3 | +package implimentation; |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public class BeautifulTriplets { |
| 10 | + private static final Scanner scanner = new Scanner(System.in); |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + int length = scanner.nextInt(); |
| 14 | + int difference = scanner.nextInt(); |
| 15 | + int[] array = getArray(length); |
| 16 | + System.out.println(beautifulTriplets(array, difference)); |
| 17 | + } |
| 18 | + |
| 19 | + private static long beautifulTriplets(int[] array, int difference) { |
| 20 | + Map<Integer, Integer> pairs = new HashMap<>(); |
| 21 | + Map<Integer, Integer> frequency = new HashMap<>(); |
| 22 | + frequency.put(array[array.length - 1], 1); |
| 23 | + long beautifulTriplets = 0; |
| 24 | + for (int index = array.length - 2 ; index >= 0 ; index--) { |
| 25 | + int number = array[index]; |
| 26 | + pairs.put(number, pairs.getOrDefault(number, 0) |
| 27 | + + frequency.getOrDefault(number + difference, 0)); |
| 28 | + beautifulTriplets += pairs.getOrDefault(number + difference, 0); |
| 29 | + frequency.put(number, frequency.getOrDefault(number, 0) + 1); |
| 30 | + } |
| 31 | + return beautifulTriplets; |
| 32 | + } |
| 33 | + |
| 34 | + private static int[] getArray(int length) { |
| 35 | + int[] array = new int[length]; |
| 36 | + for (int index = 0 ; index < length ; index++) { |
| 37 | + array[index] = scanner.nextInt(); |
| 38 | + } |
| 39 | + return array; |
| 40 | + } |
| 41 | +} |
0 commit comments