Ways to choose three points with distance between the most distant points <= L |  ; def countTripletsLessThanL ( n , L , arr ) : ; arr = sorted ( arr ) ; ways = 0 ; for i in range ( n ) : ; indexGreater = upper_bound ( arr , 0 , n , arr [ i ] + L ) ; ; numberOfElements = indexGreater - ( i + 1 ) ; ; if ( numberOfElements >= 2 ) : ways += ( numberOfElements * ( numberOfElements - 1 ) / 2 ) ; return ways ; def upper_bound ( a , low , high , element ) : while ( low < high ) : middle = int ( low + ( high - low ) / 2 ) ; if ( a [ middle ] > element ) : high = middle ; else : low = middle + 1 ; return low ; ; if __name__ == ' _ _ main _ _ ' : set of n points on the X axis
Returns the number of triplets with the NEW_LINE distance between farthest points <= L NEW_LINE INDENT sort the array NEW_LINE INDENT find index of element greater than arr [ i ] + L NEW_LINE find Number of elements between the ith NEW_LINE index and indexGreater since the Numbers NEW_LINE are sorted and the elements are distinct NEW_LINE from the points btw these indices represent NEW_LINE points within range ( a [ i ] + 1 and a [ i ] + L ) NEW_LINE both inclusive NEW_LINE if there are at least two elements in between NEW_LINE i and indexGreater find the Number of ways NEW_LINE to select two points out of these NEW_LINE DEDENT DEDENT Driver Code NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE L = 4 ; NEW_LINE ans = countTripletsLessThanL ( n , L , arr ) ; NEW_LINE print ( " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " , ans ) ; NEW_LINE DEDENT