GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Maximum number of coins you can gather.

Given N balloons, if you burst ith balloon you get Ai−1∗Ai∗Ai+1 coins and then (i-1)th and (i+1)th balloons become adjacent. Find maximum number of coins you can gather.

Assume that we have extra 1 at left most and right most positions. (don't take in answer just for boundary positions)

Hence if we have left or right boundary positions we multiply 1.

asked Nov 25, 2015 by Gaurav

2 Answers

Read about matrix chain multiplication. This essentially reduces to that.
answered Nov 29, 2015 by anonymous 1 flag

Can we do it using heaps as well? 

Maintain left and right pointers for each balloon. 

Put all the elements except the first and last in a min heap .

Then pop the elements and add the sum obtained upon each popping off of the element. Also simultaneously update the left and right indices for the right and left balloons of the current popped of balloon respectively.

If there are more than 2 balloons with the same value then select the one which has a larger valued neighbour.

At the end just remove the smaller of the 2 corner elements and then the larger corner element.