We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We have to find out minimum cost.
First, sort the array in descending order and then give each flower in the descending order to customers. After all customer gets one flower. Again start from first customer to give the remaining flowers till everyone gets second flower. But, this process should continue till all the flowers are finished.
Example:
5 Flowers and 3 Customers.
Cost of 5 Flowers: [1 3 5 7 9]
Sort in Descending order: [9 7 5 3 1]
Explanation:
Now, Pass each flower to customer till all the customer get each flower. Then, pass second rotation till all the customer get 2nd Flower.
1st Customer will get 9, 3.
2nd Customer will get 7, 1.
3rd Customer will get only 5. It can't get the second flower, as flowers count is 5.
// Convert the array to List.
List<Integer> cList = new ArrayList<Integer>();
for (int index = 0; index < c.length; index++) {
cList.add(c[index]);
}
// Sort in Descending Order.
Collections.sort(cList, Collections.reverseOrder());
// Previous Flower Count
int prev = -1;
// Cost
long cost = 0;
int size = cList.size();
int i = 0;
for (Integer fCost: cList) {
// Increase the Previous
if (i % k == 0) {
++prev;
}
cost += (fCost * (prev + 1)) ;
++i;
}
return (int) cost;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Greedy Florist
You are viewing a single comment's thread. Return to all comments →
In Java
Passed 100% test Cases
We have to find out minimum cost. First, sort the array in descending order and then give each flower in the descending order to customers. After all customer gets one flower. Again start from first customer to give the remaining flowers till everyone gets second flower. But, this process should continue till all the flowers are finished.
Example: 5 Flowers and 3 Customers. Cost of 5 Flowers: [1 3 5 7 9] Sort in Descending order: [9 7 5 3 1]
Explanation: Now, Pass each flower to customer till all the customer get each flower. Then, pass second rotation till all the customer get 2nd Flower. 1st Customer will get 9, 3. 2nd Customer will get 7, 1. 3rd Customer will get only 5. It can't get the second flower, as flowers count is 5.
Cost for each customer: 1st Customer: 9 + 3 * (1 + 1) = 15, 2nd Customer: 7 + 1 * (1 + 1) = 9, 3rd Customer: 5
Total Cost: 15 + 9 + 5 = 29