Count Good Triplets

Given an array of integers arr, and three integers ab and c. You need to find the number of good triplets.

A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

  • 0 <= i < j < k < arr.length
  • |arr[i] - arr[j]| <= a
  • |arr[j] - arr[k]| <= b
  • |arr[i] - arr[k]| <= c

Where |x| denotes the absolute value of x.

Find the number of good triplets.


Example 1:

Input: arr = {3,0,1,1,9,7}, a = 7, b = 2, c = 3
Output: 4

Approach

Java


public class CountGoodTriplets {
    public static void main(String[] args) {
        int arr[] = { 301197 };
        int a = 7, b = 2, c = 3;
        System.out.println(countGoodTriplets(arr, a, b, c));
    }

    // function to count all good pairs
    static int countGoodTriplets(int[] arrint aint bint c) {
        int cnt = 0;
        int n = arr.length;
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                if (Math.abs(arr[i] - arr[j]) <= a) {
                    for (int k = j + 1; k < n; k++) {
                        if (Math.abs(arr[j] - arr[k]) <= b &&
                         Math.abs(arr[i] - arr[k]) <= c)
                            cnt++;
                    }
                }
            }
        }
        return cnt;
    }
}

C++

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


//function to count all good pairs
int countGoodTriplets(vector<int>& arrint aint bint c
{
       int cnt=0;
        int n=arr.size();
        for(int i=0;i<n-2;i++)
        {
            for(int j=i+1;j<n-1;j++)
            {
                if(abs(arr[i]-arr[j])<=a)
                {
                for(int k=j+1;k<n;k++)
                {
                    if(abs(arr[j]-arr[k])<=b&&abs(arr[i]-arr[k])<=c)
                          cnt++;
                }
                }
            }
        }
        return cnt;
}
int main()
{
  vector<intarr ={3,0,1,1,9,7};
  int a = 7b = 2c = 3;
  cout<<countGoodTriplets(arr,a,b,c);
  return 0;
}



No comments:

Post a Comment