Print triplets with sum less than k | PHP 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
< ? php function printTriplets ( $ arr , $ n , $ sum ) { sort ( $ arr , 0 ) ; for ( $ i = 0 ; $ i < $ n - 2 ; $ i ++ ) { $ j = $ i + 1 ; $ k = $ n - 1 ; while ( $ j < $ k ) { if ( $ arr [ $ i ] + $ arr [ $ j ] + $ arr [ $ k ] >= $ sum ) $ k -- ; else { for ( $ x = $ j + 1 ; $ x <= $ k ; $ x ++ ) echo $ arr [ $ i ] . " , " ▁ . ▁ $ arr [ $ j ] ▁ . STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL " , " ▁ . ▁ $ arr [ $ x ] ▁ . ▁ " " $ j ++ ; } } } } $ arr = array ( 5 , 1 , 3 , 4 , 7 ) ; $ n = sizeof ( $ arr ) ; $ sum = 12 ; printTriplets ( $ arr , $ n , $ sum ) ; ? >