Created
August 15, 2020 12:47
-
-
Save vinodjayachandran/e33ffb9b288ca5878ad3641fda6f3ded to your computer and use it in GitHub Desktop.
Count the triplets - Given an array of distinct integers. The task is to count all the triplets such that sum of two elements equals the third element.
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
import java.util.ArrayList; | |
import java.util.Collections; | |
public class CountTriplets { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
ArrayList<Integer> inputList = new ArrayList<Integer>(); | |
for (int i = 0; i < args.length; i++) { | |
inputList.add(Integer.parseInt(args[i])); | |
} | |
Collections.sort(inputList); | |
int numOfTriplets=0; | |
for (int i = 2; i < inputList.size(); i++) { | |
int currentSum = inputList.get(i); | |
for(int j=i-1;j>0;j--) { | |
int currentNum = inputList.get(j); | |
if(inputList.subList(0, j).contains(currentSum-currentNum)) { | |
numOfTriplets++; | |
} | |
} | |
} | |
System.out.println("Total Number of Triplets " + numOfTriplets); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment