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 ] ; ; Driver Code ; set of n points on the X axis
def countTripletsLessThanL ( n , L , arr ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ways = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT mostDistantDistance = arr [ k ] - arr [ i ] NEW_LINE if ( mostDistantDistance <= L ) : NEW_LINE INDENT ways += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ways NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE L = 3 NEW_LINE ans = countTripletsLessThanL ( n , L , arr ) NEW_LINE print ( " Total ▁ Number ▁ of ▁ ways ▁ = " , ans ) NEW_LINE DEDENT