zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if and
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P
If O(N³)
is acceptable time complexity then the Pseudocode below should work. If you have stricter time complexity requirements then you'll have to specify them.
for (P in A){
for (Q in A){
for (R in A){
if(A[P] > 0 && A[Q] > 0 && A[R] > 0){
if(A[P] > A[R] - A[Q] && A[Q] > A[P] - A[R] && A[R] > A[Q] - A[P]){
return 1;
}
}
}
}
}
return 0;
The reasoning behind the if statements is this:
Since the ints can be anything up to max int you have to deal with overflow. Adding them together could cause a weird error if there are two very large ints in the array. So instead we test if they are positive and then rewrite the formulae to do the same checks, but with subtraction. We don't need to do anything if any of the values are negative or 0, since:
Assume x <= 0
Assume x+y > z
Assume x+z > y
Then y > z and z > y which is a contradiction
So no negative or zero valued ints will be a part of a triple