Skip to content

Instantly share code, notes, and snippets.

@adityamangal1
Created June 29, 2021 06:17
Show Gist options
  • Save adityamangal1/60a90e272969f6749e11b0f26ea7768a to your computer and use it in GitHub Desktop.
Save adityamangal1/60a90e272969f6749e11b0f26ea7768a to your computer and use it in GitHub Desktop.
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[], int N)
{
// Sort the array
sort(arr, arr + N);
// Stores count of triplets
int l, r, i, j, ans = 0;
// Iterate over the range [1, N]
for (i = 0; i < N; i++) {
// Iterate over the range [i+1, N]
for (j = i + 1; j < N; j++) {
// Required difference
int x = arr[j] - arr[i];
// Find lower bound of arr[j] + x
// and upper bound of arr[j] + 2*x
l = lower_bound(arr, arr + N, arr[j] + x) - arr;
r = upper_bound(arr, arr + N, arr[j] + 2 * x)
- arr;
// Adjust the indexing of arr[j]+2*r
if (r == N || arr[r] != arr[j] + 2 * x)
r -= 1;
// From l to r, count number of
// triplets by using arr[i] and arr[j]
ans += r - l + 1;
}
}
// return main ans
return ans;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
int ans = countTriplets(arr, N);
cout << ans;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment