fork download
  1. // logic for counting triplets in an array where the middle element is smaller than both the other two elements
  2. // Implemented in Python for clarity
  3. // just count the greater elem on left and right for each middle element
  4. /*
  5.   for j in range(1, n - 1): # j is the middle element
  6.   count_greater_left = 0
  7.   count_greater_right = 0
  8.  
  9.   # Count elements greater than arr[j] on the left
  10.   for i in range(j):
  11.   if arr[i] > arr[j]:
  12.   count_greater_left += 1
  13.  
  14.   # Count elements greater than arr[j] on the right
  15.   for k in range(j + 1, n):
  16.   if arr[k] > arr[j]:
  17.   count_greater_right += 1
  18.  
  19.   # Update triplet count
  20.   triplet_count += count_greater_left * count_greater_right
  21.  
  22.   return triplet_count
  23.  
  24. # Example usage
  25. arr = [5, 3, 4, 2, 1]
  26. print(count_triplets(arr)) # Output: Number of valid triplets
  27. */
  28.  
  29. import java.util.*;
  30. class TripletCounter {
  31.  
  32. public static int countTriplets(int[] arr) {
  33. int n = arr.length;
  34. int tripletCount = 0;
  35.  
  36. // Iterate through each element as the middle element
  37. for (int j = 1; j < n - 1; j++) {
  38. int countGreaterLeft = 0;
  39. int countGreaterRight = 0;
  40.  
  41. // Count elements greater than arr[j] on the left
  42. for (int i = 0; i < j; i++) {
  43. if (arr[i] > arr[j]) {
  44. countGreaterLeft++;
  45. }
  46. }
  47.  
  48. // Count elements greater than arr[j] on the right
  49. for (int k = j + 1; k < n; k++) {
  50. if (arr[k] > arr[j]) {
  51. countGreaterRight++;
  52. }
  53. }
  54.  
  55. // Update triplet count
  56. tripletCount += countGreaterLeft * countGreaterRight;
  57. }
  58.  
  59. return tripletCount;
  60. }
  61.  
  62. public static void main(String[] args) {
  63. int[] arr = {5, 3, 4, 2, 1};
  64. int result = countTriplets(arr);
  65. System.out.println("Number of valid triplets: " + result);
  66. }
  67. }
  68.  
Success #stdin #stdout 0.12s 55680KB
stdin
Standard input is empty
stdout
Number of valid triplets: 1