-3

Piles of coins are given (ex. 5 piles : 9,0,5,1,5 ) total 20 coins.. The minimum no. of moves required so that all piles have equal no of coins (4,4,4,4,4) (ans for this is 9 moves) Rules: one coin can be moved to only adjacent piles..i.e. jth pile coin can be moved to j-1 or j+1 if they exist.

any good algorithm for solving puzzle ?

atlas
  • 5
  • 1

1 Answers1

1

The arithmetic mean of all pile's sizes gives you the desired size of each pile, let it be d, while number of piles n. Let's at first assume than while constructing the solution we can sometimes have piles of negative size, and we will fix that assumption in a moment.

O(n) algorithm is as follows - let's look at the first pile. If it has size d, then we neither want to change it's size, nor to pass coins through it other piles, since there are no piles on the left. That means no move in an optimal solution will ever change this pile's size, and we can forget about it. If however the first pile's size was d' > d, then we know that we want to remove (d' - d) coins from it. As they can go only one way - to the right, we can do it, decreasing the first pile to d, and forget about it as we did before. Similarly if d' < d, then at some point in time we'll have to take some coins from the second pile, so we do it, and forget about the first pile.

As we forgot the first pile we could imagine that we deleted it, and the second one is now the first. We proceed with this process through all the piles, when moving some coins we add those moves to some counter.

There is one problem left - negative piles. Let's list all the operations we did in our solution, it's easy to see that the order in which we'll execute then does not matter. The only moves in which we could have done something illegal were those when we took coins from pile (i+1) to pile i, and may have left (i+1) negative. That means that later we took some coins from (i+2) to (i+1) to compensate it, and if this move has been done before the move taking from (i+1) then (i+1)'s size won't ever be negative. So if we'll execute the scheduled moves starting from the rightmost one, everything will be fine - that proves that the constructed solution is valid.

Cris
  • 162
  • 1
  • 8