Number of triangles possible with given lengths of sticks which are powers of 2 | Function to return the number of positive area triangles ; To store the count of total triangles ; To store the count of pairs of sticks with equal lengths ; Back - traverse and count the number of triangles ; Count the number of pairs ; If we have one remaining stick and we have a pair ; Count 1 triangle ; Reduce one pair ; Count the remaining triangles that can be formed ; Driver code
function countTriangles ( a , n ) { var cnt = 0 ; var pairs = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { pairs += a [ i ] / 2 ; if ( a [ i ] % 2 == 1 && pairs > 0 ) { cnt += 1 ; pairs -= 1 ; } } cnt += parseInt ( ( 2 * pairs ) / 3 ) ; return cnt ; } var a = [ 1 , 2 , 2 , 2 , 2 ] ; var n = a . length ; document . write ( countTriangles ( a , n ) ) ;