Count Triplets such that one of the numbers can be written as sum of the other two | Function to count the number of ways to choose the triples ; compute the max value in the array and create frequency array of size max_val + 1. We can also use HashMap to store frequencies . We have used an array to keep remaining code simple . ; Case 1 : 0 , 0 , 0 ; Case 2 : 0 , x , x ; Case 3 : x , x , 2 * x ; Case 4 : x , y , x + y iterate through all pairs ( x , y ) ; Driver code
< ? php function countWays ( $ arr , $ n ) { $ max_val = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ max_val = max ( $ max_val , $ arr [ $ i ] ) ; $ freq = array_fill ( 0 , $ max_val + 1 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ freq [ $ arr [ $ i ] ] ++ ; $ ans += ( int ) ( $ freq [ 0 ] * ( $ freq [ 0 ] - 1 ) * ( $ freq [ 0 ] - 2 ) / 6 ) ; for ( $ i = 1 ; $ i <= $ max_val ; $ i ++ ) $ ans += ( int ) ( $ freq [ 0 ] * $ freq [ $ i ] * ( $ freq [ $ i ] - 1 ) / 2 ) ; for ( $ i = 1 ; 2 * $ i <= $ max_val ; $ i ++ ) $ ans += ( int ) ( $ freq [ $ i ] * ( $ freq [ $ i ] - 1 ) / 2 * $ freq [ 2 * $ i ] ) ; for ( $ i = 1 ; $ i <= $ max_val ; $ i ++ ) { for ( $ j = $ i + 1 ; $ i + $ j <= $ max_val ; $ j ++ ) $ ans += $ freq [ $ i ] * $ freq [ $ j ] * $ freq [ $ i + $ j ] ; } return $ ans ; } $ arr = array ( 1 , 2 , 3 , 4 , 5 ) ; $ n = count ( $ arr ) ; echo countWays ( $ arr , $ n ) ; ? >