HackerRank Greedy Florist
Luciano Pinheiro
Posted on August 31, 2023
This is the solution for the HackerRank Greedy Florist problem, in python. This is a problem in the Interview Preparation Kit > Greedy Algorithms and is considered medium.
The problem is as follows:
- The greedy florist wants to maximize his price
- He has a formula to the price: (n + 1) * original price
- n is the number of flowers previously purchased
So, if you buy one flower, it will be the original price. If you buy a second flower, the price is 2 * original price.
I think that the problem never left clear that the expensive flowers must be purchased first, but that's in the answer.
Solution
The first problem we must solve is to put the array in a reverse price order.
c.sort()
c.reverse()
So we can traverse it and buy the flowers. For each item, we must find:
- n
- current cost
We can find n
by integer (or floor) dividing the array position with the number of friends k
for i in range(len(c)):
n = i // k
So, the first round of purchases will have n = 0, the second, n = 1, and so on.
The cost is straight to the formula:
flower_cost = c[i]
cost = (n + 1) * flower_cost
And that's it. The complete solution is as follow:
def getMinimumCost(k, c):
total = 0
c.sort()
c.reverse()
for i in range(len(c)):
n = i//k
flower_cost = c[i]
cost = (n + 1) * flower_cost
total += cost
return total
Posted on August 31, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.