Ways to choose three points with distance between the most distant points <= L | C ++ program to count ways to choose triplets such that the distance between the farthest points <= L ; Returns the number of triplets with distance between farthest points <= L ; sort to get ordered triplets so that we can find the distance between farthest points belonging to a triplet ; generate and check for all possible triplets : { arr [ i ] , arr [ j ] , arr [ k ] } ; Since the array is sorted the farthest points will be a [ i ] and a [ k ] ; ; Driver Code ; set of n points on the X axis
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTripletsLessThanL ( int n , int L , int * arr ) { sort ( arr , arr + n ) ; int ways = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { int mostDistantDistance = arr [ k ] - arr [ i ] ; if ( mostDistantDistance <= L ) { ways ++ ; } } } } return ways ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 3 ; int ans = countTripletsLessThanL ( n , L , arr ) ; cout << " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " << ans << " STRNEWLINE " ; return 0 ; }