DEV Community

Luciano Pinheiro
Luciano Pinheiro

Posted on

HackerRank Greedy Florist

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)