Count number of triplets in an array having sum in the range [ a , b ] | Java program to count triplets with sum that lies in given range [ a , b ] . ; Function to find count of triplets having sum less than or equal to val . ; sort the input array . ; Initialize result ; to store sum ; Fix the first element ; 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 greater , then to reduce it decrease k . ; If sum is less than or equal to given value , then add possible triplets ( k - j ) to result . ; Function to return count of triplets having sum in range [ a , b ] . ; to store count of triplets . ; Find count of triplets having sum less than or equal to b and subtract count of triplets having sum less than or equal to a - 1. ; Driver Code
import java . util . * ; class GFG { public static int countTripletsLessThan ( int [ ] arr , int n , int val ) { Arrays . sort ( arr ) ; int ans = 0 ; int j , k ; int sum ; for ( int i = 0 ; i < n - 2 ; i ++ ) { j = i + 1 ; k = n - 1 ; while ( j != k ) { sum = arr [ i ] + arr [ j ] + arr [ k ] ; if ( sum > val ) k -- ; else { ans += ( k - j ) ; j ++ ; } } } return ans ; } public static int countTriplets ( int arr [ ] , int n , int a , int b ) { int res ; res = countTripletsLessThan ( arr , n , b ) - countTripletsLessThan ( arr , n , a - 1 ) ; return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 } ; int n = arr . length ; int a = 8 , b = 16 ; System . out . println ( " " + countTriplets ( arr , n , a , b ) ) ; } }