AlgoDesign

Greedy florist

1def getMinimumCost(k, c):
2  numFlowers = len(c)
3  # if numFlowers <= k: sort c in ascending order and return the sum of c[:numFlowers]
4  # else:
5  # for i in range(k): add the most expensive flowers and numFlowers -= 1
6  # for i in range(numFlowers): add the least expensive flowers and numFlowers -= 1
7  c.sort()
8  if numFlowers <= k: return sum(c[:numFlowers])
9  else:
10    res, lastFlower = 0, len(c) - 1
11    kBought = []
12    for i in range(k): 
13      res += c[-(i + 1)]
14      heappush(kBought, 1)
15      lastFlower -= 1
16      numFlowers -= 1
17    
18    i = lastFlower
19    while numFlowers > 0:
20      minKBoughtFlowers = heappop(kBought)
21      res += (minKBoughtFlowers + 1) * c[lastFlower]
22      heappush(kBought, minKBoughtFlowers + 1)
23      lastFlower -= 1
24      numFlowers -= 1
25    
26    return res