Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr [ i ] and arr [ j ] . All elements between arr [ j + 1 ] to arr [ k - 1 ] can form a triangle with arr [ i ] and arr [ j ] . One is subtracted from k because k is incremented one extra in above while loop . k will always be greater than j . If j becomes equal to k , then above loop will increment k , because arr [ k ] + arr [ i ] is always / greater than arr [ k ]
if ( k > j ) count += k - j - 1 ; } } return count ; }