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
< ? php function maxCandies ( $ arr , $ n ) { $ prevBought = $ arr [ $ n - 1 ] ; $ candies = $ prevBought ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { $ x = min ( $ prevBought - 1 , $ arr [ $ i ] ) ; if ( $ x >= 0 ) { $ candies += $ x ; $ prevBought = $ x ; } } return $ candies ; } $ arr = array ( 1 , 2 , 1 , 3 , 6 ) ; $ n = sizeof ( $ arr ) ; echo ( maxCandies ( $ arr , $ n ) ) ; ? >