Count the number of possible triangles | C ++ implementation of the above approach ; CountTriangles function ; If it is possible with a [ l ] , a [ r ] and a [ i ] then it is also possible with a [ l + 1 ] . . a [ r - 1 ] , a [ r ] and a [ i ] ; checking for more possible solutions ; if not possible check for higher values of arr [ l ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountTriangles ( vector < int > A ) { int n = A . size ( ) ; sort ( A . begin ( ) , A . end ( ) ) ; int count = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int l = 0 , r = i - 1 ; while ( l < r ) { if ( A [ l ] + A [ r ] > A [ i ] ) { count += r - l ; r -- ; } else l ++ ; } } cout << " No ▁ of ▁ possible ▁ solutions : ▁ " << count ; } int main ( ) { vector < int > A = { 4 , 3 , 5 , 7 , 6 } ; CountTriangles ( A ) ; }