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
def bit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += 1 NEW_LINE n = n & ( n - 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def maxSumOfBits ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = bit ( arr [ i ] ) NEW_LINE DEDENT incl = arr [ 0 ] NEW_LINE excl = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if incl > excl : NEW_LINE INDENT excl_new = incl NEW_LINE DEDENT else : NEW_LINE INDENT excl_new = excl NEW_LINE DEDENT incl = excl + arr [ i ] ; NEW_LINE excl = excl_new NEW_LINE DEDENT if incl > excl : NEW_LINE INDENT return incl NEW_LINE DEDENT else : NEW_LINE INDENT return excl NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 , 6 , 7 , 20 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSumOfBits ( arr , n ) ) NEW_LINE DEDENT