Count triplet in java
Task -
You will be given an array and a number and you need to find the number of triplet in the array whose sum is equal to given number in the input.
Input Format -
you will be taking a number as an input from STDIN which tells about the length of the array. On another line, array elements should be there with single space between them. Next line should have a integer value.
Output Format -
you need to print the number of triplet of integers in the array whose sum is equal to the given integer.
Sample Test Case:
Sample Input:-4
2 5 7 -1
6
Sample Output -
1
Explanation:
There is 1 triplet with sum 6 which is (2, 5, -1). So, output is 1.
You will be given an array and a number and you need to find the number of triplet in the array whose sum is equal to given number in the input.
Input Format -
you will be taking a number as an input from STDIN which tells about the length of the array. On another line, array elements should be there with single space between them. Next line should have a integer value.
Output Format -
you need to print the number of triplet of integers in the array whose sum is equal to the given integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* You will be given an array and a number and you need to find the | |
* number of triplet in the array whose sum is equal to given number in the input. | |
*/ | |
import java.io.*; | |
import java.util.*; | |
public class CandidateCode { | |
public static void main(String args[] ) throws Exception { | |
Scanner sc=new Scanner(System.in); | |
int size; | |
size=sc.nextInt(); | |
int [] arr=new int[size]; | |
for(int i=0;i<size;i++){ | |
arr[i]=sc.nextInt(); | |
} | |
int find=sc.nextInt(); | |
int sum=0,count=0; | |
for(int a=0,b=a+1,c=b+1;a<arr.length&&b<arr.length&&c<arr.length;a++,b++,c++){ | |
int x=arr[a],y=arr[b],z=arr[c]; | |
sum=x+y+z; | |
if(sum==find){ | |
count++; | |
} | |
} | |
System.out.println(count); | |
sc.close(); | |
} | |
} |
Sample Test Case:
Sample Input:-4
2 5 7 -1
6
Sample Output -
1
Explanation:
There is 1 triplet with sum 6 which is (2, 5, -1). So, output is 1.
Comments
Post a Comment