I was stuck in solving the following interview practice question:
I have to write a function:
int triangle(int[] A);
that given a zero-
public static int solution(int[] A) {
// write your code in Java SE 8
long p, q, r;
int isTriangle = 0;
Arrays.sort(A);
for (int i = 0; i < A.length; i += 1) {
if (i + 2 < A.length) {
p = A[i];
q = A[i + 1];
r = A[i + 2];
if (p >= 0) {
if (Math.abs(p) + Math.abs(q) > Math.abs(r) && Math.abs(q) + Math.abs(r) > Math.abs(p) && Math.abs(r) + Math.abs(p) > Math.abs(q))
return 1;
}
} else return 0;
}
return isTriangle;
}
The above implementation is Linear in time complexity. The concept is simple use the formaula they gave extracting a series of triplets of sorted elements.