Determine whether a triangle can be built from a given set of edges
By sorting the array, we have guaranteed that P+R < Q and Q+R < P (because R is always the biggest). Now what remains, is the proof that P+Q > R, that can be found out by traversing the array. The chance to find such a combination is with three adjacent values as they provide the highest P and Q.
JavaScript
function solution(A) {
// write your code in JavaScript (Node.js 6.4.0)
var sumUp, sumDown;
for (var i=0, len = A.length; i < len; i++) {
sumUp =0;
sumDown=0;
for (j=0; j<i; j++) {
sumUp += A[j];
}
for (k=(A.length-1); k>i; k--) {
sumDown += A[k];
}
if (sumUp === sumDown) {
return i;
}
}
}
solution([-1, 3, -4, 5, 1, -6, 2, 1]);