Ways to choose three points with distance between the most distant 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 ] ; ; set of n points on the X axis
< ? php function countTripletsLessThanL ( $ n , $ L , $ arr ) { sort ( $ arr ) ; $ ways = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = $ i + 1 ; $ j < $ n ; $ j ++ ) { for ( $ k = $ j + 1 ; $ k < $ n ; $ k ++ ) { $ mostDistantDistance = $ arr [ $ k ] - $ arr [ $ i ] ; if ( $ mostDistantDistance <= $ L ) { $ ways ++ ; } } } } return $ ways ; } $ arr = array ( 1 , 2 , 3 , 4 ) ; $ n = sizeof ( $ arr ) ; $ L = 3 ; $ ans = countTripletsLessThanL ( $ n , $ L , $ arr ) ; echo " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " , $ ans , " STRNEWLINE " ; ? >