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
function maxCandies ( arr , n ) { let prevBought = arr [ n - 1 ] ; let candies = prevBought ; for ( let i = n - 2 ; i >= 0 ; i -- ) { let x = Math . min ( prevBought - 1 , arr [ i ] ) ; if ( x >= 0 ) { candies += x ; prevBought = x ; } } return candies ; } let arr = [ 1 , 2 , 1 , 3 , 6 ] ; let n = arr . length ; document . write ( maxCandies ( arr , n ) ) ;