You and your K-1 friends want to buy N flowers. Flower number i has host ci. Unfortunately the seller does not like a customer to buy a lot of flowers, so he tries to change the price of flowers for customer who had bought flowers before. More precisely if a customer has already bought x flowers, he should pay (x+1)*ci dollars to buy flower number i.
You and your K-1 firends want to buy all N flowers in such a way that you spend the as few money as possible.
You and your K-1 firends want to buy all N flowers in such a way that you spend the as few money as possible.
we can get minimum cost only if the cost (x+1)*ci is minimum. That means X should be minimum and ci should also be minimum. So this indicates that each person should buy flowers uniformly. We cannot have person A buying 3 flowers and person B buying only 1. So we should use round-robin algorithm here - each person buy one flower at a time. And to make ci minimum means, we need to buy low cost flowers later. That means start buying high cost flowers and then move to low cost ones.
So we arrive at a solution - Sort the costs and use round-robin
Read full article from Break the CODE!!!: Interviewstreet Challenge: FlowersCollections.sort(set);int[] counters = new int[k];int total = 0;int i=0;while(!set.isEmpty()) {int m = set.size() - 1;int val = set.remove(m);total = total + (1+counters[i])*val;counters[i] = counters[i] + 1;if( i < k-1 ) {i++;} else {i=0;}}