Print triplets with sum less than k | Java 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
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void printTriplets ( int arr [ ] , int n , int sum ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { int j = i + 1 , k = n - 1 ; while ( j < k ) { if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) k -- ; else { for ( int x = j + 1 ; x <= k ; x ++ ) System . out . println ( arr [ i ] + " , ▁ " + arr [ j ] + " , ▁ " + arr [ x ] ) ; j ++ ; } } } } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 1 , 3 , 4 , 7 } ; int n = arr . length ; int sum = 12 ; printTriplets ( arr , n , sum ) ; } }