Count triplets with sum smaller than a given value | A Simple Javascript program to count triplets with sum smaller than a given value ; Sort input array ; Initialize result ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there can be total k - j third elements . ; Driver method to test the above function
let arr = [ 5 , 1 , 3 , 4 , 7 ] ; function countTriplets ( n , sum ) { arr . sort ( function ( a , b ) { return b - a } ) ; let ans = 0 ; for ( let i = 0 ; i < n - 2 ; i ++ ) { let j = i + 1 , k = n - 1 ; while ( j < k ) { if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) k -- ; else { ans += ( k - j ) ; j ++ ; } } } return ans ; } let sum = 12 ; document . write ( countTriplets ( arr . length , sum ) ) ;