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
function countTripletsLessThanL ( n , L , arr ) { arr . sort ( ) ; var ways = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { for ( k = j + 1 ; k < n ; k ++ ) { var mostDistantDistance = arr [ k ] - arr [ i ] ; if ( mostDistantDistance <= L ) { ways ++ ; } } } } return ways ; } var arr = [ 1 , 2 , 3 , 4 ] ; var n = arr . length ; var L = 3 ; var ans = countTripletsLessThanL ( n , L , arr ) ; document . write ( " " + ans ) ;