Maximize the sum of selected numbers from an array to make it empty | function to maximize the sum of selected numbers ; maximum in the sequence ; stores the occurrences of the numbers ; marks the occurrence of every number in the sequence ; ans to store the result ; Using the above mentioned approach ; if occurence is greater than 0 ; add it to ans ; decrease i - 1 th element by 1 ; decrease ith element by 1 ; decrease i ; Driver code
def maximizeSum ( a , n ) : NEW_LINE INDENT maximum = max ( a ) NEW_LINE ans = dict . fromkeys ( range ( 0 , n + 1 ) , 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ a [ i ] ] += 1 NEW_LINE DEDENT result = 0 NEW_LINE i = maximum NEW_LINE while i > 0 : NEW_LINE INDENT if ans [ i ] > 0 : NEW_LINE INDENT result += i ; NEW_LINE ans [ i - 1 ] -= 1 ; NEW_LINE ans [ i ] -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT i -= 1 ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( maximizeSum ( a , n ) ) NEW_LINE DEDENT