Maximum set bit sum in array without considering adjacent elements | Function to count total number of set bits in an integer ; Maximum sum of set bits ; Calculate total number of set bits for every element of the array ; find total set bits for each number and store back into the array ; current max excluding i ; current max including i ; return max of incl and excl ; Driver code
< ? php function bit ( $ n ) { $ count = 0 ; while ( $ n ) { $ count ++ ; $ n = $ n & ( $ n - 1 ) ; } return $ count ; } function maxSumOfBits ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ arr [ $ i ] = bit ( $ arr [ $ i ] ) ; } $ incl = $ arr [ 0 ] ; $ excl = 0 ; $ excl_new ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ excl_new = ( $ incl > $ excl ) ? $ incl : $ excl ; $ incl = $ excl + $ arr [ $ i ] ; $ excl = $ excl_new ; } return ( ( $ incl > $ excl ) ? $ incl : $ excl ) ; } $ arr = array ( 1 , 2 , 4 , 5 , 6 , 7 , 20 , 25 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo maxSumOfBits ( $ arr , $ n ) ; #This  Code is Contributed by ajit  NEW_LINE ? >