## Amazon Interview Question

Software Developers**Country:**India

public static int moves(int COINS[]) {

int moves = 0;

for(int i =0; i < COINS.length-1; i++) {

if(COINS[i] > 0 && COINS[i+1] > 0) {

moves++;

}

if(COINS[i] == 0) {

moves++;

}

}

if(COINS[COINS.length-1] == 0) {

moves++;

}

return moves;

}

```
const coinSack = {};
coinSack.stacks = [0,1,2,3,0,0,25,2,1,0];
coinSack.getStackCount = () => coinSack.stacks.length;
coinSack.getCoinCount = () => coinSack.stacks.reduce((total, amount) => total + amount );
coinSack.getStackAverageCoinCount = () => (coinSack.getCoinCount() / coinSack.stacks.length).toFixed();
coinSack.calcDistributeCoinsTransactionCount = (minimumCoinsPerStack) => {
//check to see if there is enough coins to distribute based on minimumCoins per stack
if ((coinSack.getStackCount() * minimumCoinsPerStack) > coinSack.getCoinCount()) {
console.log('Not enough coins to distribute.');
return;
}
return coinSack.stacks.filter(stack => stack < minimumCoinsPerStack).length;
};
console.log(coinSack.calcDistributeCoinsTransactionCount(2));
});
```

A greedy approach can work here. The idea is that we keep track of how many incomplete stacks there are to the left of position i (shortage array). Note that shortage[-1] - shortage[i] also gives us the information on the number of incomplete stacks to the right of position i. Then for every stack where we have some extra coins (>1) we calculate how many needs to be moved left / right based on our knowledge of incomplete stacks:

Test driver:

- adr October 07, 2018