Given a sequence of integers , a triplet  is beautiful if:
Given an increasing sequence of integers and the value of , count the number of beautiful triplets in the sequence.
For example, the sequence  and . There are three beautiful triplets, by index: . To test the first triplet,  and .
Description
 It must return an integer that represents the number of beautiful triplets in the sequence.
beautiful triplets has the following parameters:
  • d: an integer
  • arr: an array of integers, sorted ascending

Input Format
The first line contains  space-separated integers  and , the length of the sequence and the beautiful difference.
The second line contains  space-separated integers .

Output Format
Print a single line denoting the number of beautiful triplets in the sequence.

Question from hackerrank.

Solution in C# -
class Solution {
    static int beautifulTriplets(int d, int[] arr) {
         int triplets = 0;
        for(int i=0; i<arr.Length-2; i++)
        {
            for(int j=i+1; j<arr.Length; j++)
            {
                if(arr[j] - arr[i] == d)
                {
                    for(int k=j+1; k<arr.Length; k++)
                        if(arr[k] - arr[j] == d)
                            triplets++;
                }
            }
        }
        return triplets;
    }
    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        string[] nd = Console.ReadLine().Split(' ');
        int n = Convert.ToInt32(nd[0]);
        int d = Convert.ToInt32(nd[1]);
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
        int result = beautifulTriplets(d, arr);
         textWriter.WriteLine(result);
        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post