Beautiful Triplets

Given a sequence of integers a, a triplet (a[i],a[j],a[k]) is beautiful if:

1. i<j<k

2 a[j] - a[i] = a[k] - a[j] = d

Given an increasing sequence of integers and the value of d, count the number of beautiful triplets in the sequence.

Example:

Input:  n=7, d=3, arr[]={1,2,4,5,7,8,10}
Output: 10

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int beautifulTriplets(int arr[], int nint d)
{
    int cnt = 0;
    for (int i = 0i <= n - 2i++)
    {
        bool pos1 = binary_search(arrarr + narr[i] + d);
        bool pos2 = binary_search(arrarr + narr[i] + 2 * d);
        if (pos1 == true && pos2 == true)
            cnt++;
    }
    return cnt;
}
int main()
{
    int n = 7d = 3;
    int arr[n] = {12457810};

    cout << beautifulTriplets(arrnd);
    return 0;
}


No comments:

Post a Comment