Given n
and an array of n
positive integers, the number of ways one can choose three numbers such that they cannot form a triangle is needed.
Example:
3
4 2 10
Answer:
1
My approach (in JAVA
)
int[] arr = new int[n];//list of the numbers given
int count=0;//count of all such triplets
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
Arrays.sort(arr);
for(int i=n-1;i>=0;i--)
{
int j=0;
int k= i-1;
while(j<k && k>=0)
{
if(arr[i]>=arr[j]+arr[k])//condition for no triangle formation
{
count++;
j++;//checking the next possible triplet by varying the third number
}
else if(arr[i]<arr[j]+arr[k])
{
j=0;
k--;//now varying the second number if no such third number exists
}
}
}
System.out.println(count);
My algorithm:
After sorting the list I am trying to find all the numbers less then arr[i]
such that arr[i]>=arr[j]+arr[k]
, in which case the triangle will not form.
But I am getting timed-out
for this solution. Could anyone suggest a better approach to this problem?