Smaller Than Triplet Sum in java

Smaller Than Triplet Sum in java

You are given an array ARR containing N integers, and you are also given an integer TARGET. You task is to find the count of triplets i, j, k ( 0 ≤ i < j < k < N ), such that ARR[i] + ARR[j] + ARR[j] is less than the value of TARGET.

For example:

If N = 7, ARR = { 1, 5, 2, 3, 4, 6, 7 } and TARGET = 9 Then, there are three triplets with sum less than 9:

  1. {1, 5, 2}
  2. {1, 2, 3}
  3. {1, 2, 4}
  4. {1, 3, 4} Thus, the output will be 4.

Input Format:

The first line contains a single integer N, denoting the size of the array.

The second line of contains N integers of the array ARR, denoting the array elements.

The third line contains a single integer TARGET, denoting the target value to evaluate the smaller sum.

Output Format:

Print the count of triplets having a sum less than the given target value.

Example 1:

Input:

7
1 5 2 3 4 6 7
9

Output:

4

Explanation:

We will print 4 because:

The following four triplets have sum less than 9: {1, 5, 2}, {1, 2, 3}, {1, 2, 4} and {1, 3, 4}.

Example 2:

Input:

6
-1 0 2 3 4 6
4

Output:

3

Explanation:

We will print 3 because:

The following three triplets have sum less than 4: {-1, 0, 2}, {-1, 0, 3} and {-1, 0, 4}.

Constraints:

1 ≤ N ≤ 1000

-100 ≤ ARR[i] ≤ 100

-100 ≤ TARGET ≤ 100

Solution of Smaller Than Triplet Sum in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{    
        static int check (int A[], int n, int p){
                int l=0,  r=n-1;
                int ans = -1;
                while(l<=r){
                        int mid = (l+r)/2;
                        if(A[mid]<p){
                                ans = mid;
                                l = mid+1;
                        }else r = mid-1;
                }
                return ans+1;
        }
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
                Scanner sc = new Scanner(System.in);
                int n = sc.nextInt();
                int A[] = new int[n];
                for(int i=0;i<n;i++){
                        A[i] = sc.nextInt();
                }
                int t = sc.nextInt();
                Arrays.sort(A);
                int count = 0;
                for(int i=0;i<n;i++){
                        for(int j=i+1;j<n;j++){
                                int x = check(A,n,t-A[i]-A[j]);
                                if(A[i]<t-A[i]-A[j])x--;
                                if(A[j]<t-A[i]-A[j])x--;
                                count += x;
                        }
                }
                System.out.println(count/3);

	}
}

Add a Comment

Your email address will not be published. Required fields are marked *