1

Given a strictly increasing sequence of n positive integers A(1) < A(2) < ... < A(n). We need to find the number of triangles with side lengths as 3 distinct elements of this sequence.

Since n <= 6000, checking every possible combination is not fast enough. Is there any better algorithm? Thanks for any help.

My pseudocode:

for i from 0 till n - 2
    for j from i+1 till n-1
        for k from j+1 till n
            if A[i] + A[j] > A[k] then count += 1
            else break
Jean Jung
  • 1,200
  • 12
  • 29
Artur
  • 591
  • 3
  • 14

1 Answers1

0
  1. You can exclude the third cycle and look for max k value with binary search. Complexity is O(N^2*Log(N)
  2. You can reach better time - O(N^2) - just think how to use monotonicity property.
MBo
  • 77,366
  • 5
  • 53
  • 86