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
function bit ( n ) { let count = 0 ; while ( n > 0 ) { count ++ ; n = n & ( n - 1 ) ; } return count ; } function maxSumOfBits ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) { arr [ i ] = bit ( arr [ i ] ) ; } let incl = arr [ 0 ] ; let excl = 0 ; let excl_new ; for ( let i = 1 ; i < n ; i ++ ) { excl_new = ( incl > excl ) ? incl : excl ; incl = excl + arr [ i ] ; excl = excl_new ; } return ( ( incl > excl ) ? incl : excl ) ; } let arr = [ 1 , 2 , 4 , 5 , 6 , 7 , 20 , 25 ] ; let n = arr . length ; document . write ( maxSumOfBits ( arr , n ) ) ;