Optimised problem 39 with triangle inequality testing