Print triplets with sum less than k | JavaScript program to print triplets with sum smaller than a given value ; Sort input array ; 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 are total k - j third elements . ; Driver Code
function printTriplets ( arr , n , sum ) { arr . sort ( function ( a , b ) { return a - b } ) ; 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 { for ( let x = j + 1 ; x <= k ; x ++ ) document . write ( arr [ i ] + " " + arr [ j ] + " " + arr [ x ] + " " ) ; j ++ ; } } } } let arr = [ 5 , 1 , 3 , 4 , 7 ] ; let n = arr . length ; let sum = 12 ; printTriplets ( arr , n , sum ) ;