Maximum number of candies that can be bought | Function to return the maximum candies that can be bought ; Buy all the candies of the last type ; Starting from second last ; Amount of candies of the current type that can be bought ; Add candies of current type that can be bought ; Update the previous bought amount ; Driver code
def maxCandies ( arr , n ) : NEW_LINE INDENT prevBought = arr [ n - 1 ] ; NEW_LINE candies = prevBought ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT x = min ( prevBought - 1 , arr [ i ] ) ; NEW_LINE if ( x >= 0 ) : NEW_LINE INDENT candies += x ; NEW_LINE prevBought = x ; NEW_LINE DEDENT DEDENT return candies ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 3 , 6 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( maxCandies ( arr , n ) ) ; NEW_LINE DEDENT